[英]How to write valid HTML out of a liquid tag?
我一直在學習如何使用 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 function / 液體標簽的返回?
您的{{ site.data.stackexchange.user.id }}
類的流動表達式不會在此處解釋。 您需要使用變量來 output 您的數據。
正如我猜測的那樣,您將數據存儲在_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 知識的人維護。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.