首页 > 解决方案 > 如何从液体标签中写入有效的 HTML?

问题描述

语境化

我一直在学习如何使用 Jekyll,现在我正在尝试开发我的第一个液体标签。它的目的是呈现给定 StackExchange 社区的我的天赋

这样,当我注入{% flair stackoverflow %}一个页面时,它应该被等效的 HTML 替换。下面是代码:

module Jekyll
    class FlairTag < Liquid::Tag

        def initialize(tag_name, community, tokens)
            super
            @community = community
        end

        def render(context)
            output = \
            "<a href=\"{{ #{@community}.url }}/users/{{ #{@community}.id }}/{{ site.data.stackexchange.user.nickname }}\">" \
                "<img src=\"https://stackexchange.com/users/flair/{{ site.data.stackexchange.user.id }}\" " \
                    "width=\"208\" height=\"58\" " \
                    "title=\"Profile for {{ site.data.stackexchange.user.nickname }} on {{ include.label }}\">" \
                    "alt=\"Profile for {{ site.data.stackexchange.user.nickname }} on {{ include.label }}\"" \
            "</a>"

            return output
        end
    end
end

Liquid::Template.register_tag('flair', Jekyll::FlairTag)

问题

我在这里读到返回一个包含所需 HTML 代码的字符串,我将实现我的目标,但是它没有正确发生,我的意思是,它与我直接在页面中编写 HTML 不同。

有什么我错过的吗?或者有另一种方式来写出 HTML 代码作为 ruby​​ 函数/液体标签的返回?

标签: htmlrubypluginsjekyllliquid

解决方案


您的流式表达 like{{ site.data.stackexchange.user.id }}不会在这里解释。您需要使用变量来输出数据。

正如我猜测的那样,您将数据存储在_data/stackoverflow.yml文件中,该文件可能如下所示:

url: https://stackoverflow.com
id: 2989289
user: artu-hnrq

这段代码将完成这项工作:

module Jekyll
    class FlairTag < Liquid::Tag

        def initialize(tag_name, community, tokens)
            super
            # if this tag is called with {% flair stackoverflow %}
            # the "community" variable will be "stackoverflow "
            # in order to remove the trailing space, we strip the variable
            @community = community.strip
        end

        def render(context)
            site = context.registers[:site]
            data = site.data[@community]
            url  = data["url"]
            id   = data["id"]
            user = data["user"]
            alt  = "Profile for #{user} on #{@community}"

            output = %(
              <a href="#{url}/users/#{id}/#{user}">
                <img src="#{url}/users/flair/#{id}.png"
                     width="208" height="58"
                     title="#{alt}"
                     alt="#{alt}"
              </a>
            )
        end
    end
end

Liquid::Template.register_tag('flair', Jekyll::FlairTag)

注意:从我的角度来看,如果此代码段位于您网站上的一个独特位置(简历、页脚、...),则可以通过简单的包含来实现。

如果不需要为每个页面定制这个标签,几乎没有性能提升,并且您的代码可以由只有 html/liquid 知识的人维护。


推荐阅读