Jekyll:为外部链接(目标和CSS类)生成自定义HTML

0__*_*0__ 10 css liquid jekyll kramdown

据我所知,CSS无法指定链接的target属性<a>.我希望能够使用以下输出在基于Jekyll的markdown文档中生成外部链接:

<a href="the-url" class="external" target="_blank">the text</a>
Run Code Online (Sandbox Code Playgroud)

诉诸这样的事情:

[the text](the url){:target"_blank" class="external"}
Run Code Online (Sandbox Code Playgroud)

我不想target在每个链接中硬编码,因为我可能想在某个时候改变它,也是吵闹.理想情况下,我会有

[the text](the url){:class="external"}
Run Code Online (Sandbox Code Playgroud)

...但是CSS无法添加target="_blank".

所以我的想法是一个允许我写的自定义插件

{% ext-link the-url the text %}
Run Code Online (Sandbox Code Playgroud)

这样的插件存在吗?有没有更好的方法来实现这一目标?

Dav*_*uel 11

当您需要在Github页面上执行此操作然后无法使用插件时,您可以使用javascript执行此操作:

// any link that is not part of the current domain is modified

(function() {
  var links = document.links;
  for (var i = 0, linksLength = links.length; i < linksLength; i++) {
    // can also be
    //  links[i].hostname != 'subdomain.example.com'
    if (links[i].hostname != window.location.hostname) {
      links[i].target = '_blank';
      links[i].className += ' externalLink';
    }
  }
})();
Run Code Online (Sandbox Code Playgroud)

灵感来自这个答案.


0__*_*0__ 10

看起来编写插件很简单.这就是我想出的:

module Jekyll
  class ExtLinkTag < Liquid::Tag
    @text = ''
    @link = ''

    def initialize(tag_name, markup, tokens)
      if markup =~ /(.+)(\s+(https?:\S+))/i
        @text = $1
        @link = $3
      end
      super
    end

    def render(context)
      output = super
      "<a class='external' target='_blank' href='"+@link+"'>"+@text+"</a>"
    end
  end
end

Liquid::Template.register_tag('extlink', Jekyll::ExtLinkTag)
Run Code Online (Sandbox Code Playgroud)

用法示例:

Exhibition at {% extlink Forum Stadtpark http://forum.mur.at %}.
Run Code Online (Sandbox Code Playgroud)

HTML输出:

<p>Exhibition at <a class="external" target="_blank" href="http://forum.mur.at">Forum Stadtpark</a>.</p>
Run Code Online (Sandbox Code Playgroud)