【问题标题】:Silverstripe Rendering External URLs as Relative LinksSilverstripe 将外部 URL 呈现为相对链接
【发布时间】:2017-11-21 03:57:57
【问题描述】:

我在 SilverStripe 将外部 URL 视为相对链接时遇到问题。

我有一个数据对象:

class Artist extends DataObject {
  private static $db = array(
    'Title' => 'Varchar(255)',
    'Content' => 'HTMLText',
    'Website' => 'Varchar(255)',
  );
}

艺术家网站通过<a href="$Website" target="_blank"> 呈现。问题是这些 URL 被附加到网站的基本 URL 上,所以我们最终得到如下内容:

<a href="mysite.com/www.artistsite.com" target="_blank">

而不是想要的:

<a href="www.artistsite.com" target="_blank">

但是,如果 $Website 包含协议(http 或 https),则链接将按预期工作。所以如果 $Website 是http://www.artistsite.com 那么我们得到:

<a href="http://www.artistsite.com" target="_blank">

本网站包含数百甚至数千条客户维护的艺术家记录。理想情况下,客户端将能够粘贴 URL,而不必担心将 http 或 https 附加到每个 URL。

有人有什么想法吗?这与SilverStripe forums 中描述的问题相同,但尚未发布解决方案。

此站点在 SilverStripe 3.6 上。

【问题讨论】:

标签: php html silverstripe


【解决方案1】:

这不是 SilverStripe 的直接问题。

给定一个包含以下内容的 html 文档:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a href="google.com" target="_blank">test</a>
<a href="www.google.com" target="_blank">test</a>

</body>
</html>

所有这些都作为网站的相对链接打开,而不是外部网址。

html - links without http protocol

为了帮助管理员粘贴功能链接,添加一个 onBeforeWrite 来测试 url 是否包含有效的协议,如果没有,至少自动添加 http://。或者使用@wmk 在评论中建议的自动执行此操作的模块。

【讨论】:

    【解决方案2】:

    由于记录已经建立,并且我不想将所有网站字段转换为不同的字段类型,我选择根据@olli-tyynelä 和@bummzack 的建议添加 onBeforeWrite:

    public function onBeforeWrite() {
      $url = $this->Website;
      if  ( $ret = parse_url($url) ) {
    
        if ( !isset($ret["scheme"]) ) {
          $url = "http://{$url}";
          $this->Website = $url;
          $this->write();
        }
      }
      parent::onBeforeWrite();
    }
    

    谢谢:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多