Jim*_*mmy 18 template-engine liquid ruby-on-rails-3
我在Liquid中创建了一个自定义链接标记,我试图将液体变量传递给该标记的调用,就像这样
{{ assign id = 'something' }} // this value is actual dynamic while looping through data
{% link_to article: id, text: 'Click Me!' %} // my custom tag
Run Code Online (Sandbox Code Playgroud)
但是,这会导致article参数按照上面的assign语句以'id'而不是'something'的形式传递.
有谁知道如何将变量传递给标签调用?
我最近通过将变量的名称作为标记参数传递,使用Jekyll 0.11.2和Liquid 2.3.0非常简单地解决了这个问题.
{% assign v = 'art' %}
{% link_to_article v %}
Run Code Online (Sandbox Code Playgroud)
您也可以在循环中传递控件var的名称,article如上所述.
在Liquid::Tag.initialize,@markup是第二个参数,标签名称后面的字符串.分配的变量位于顶层context.
def render(context)
"/#{context[@markup.strip]}/"
end
Run Code Online (Sandbox Code Playgroud)
这显然只允许传递一个参数.更复杂的解决方案会解析params之类的问题x: 2, y: 3.
看来这是不可能的,我的解决方案是将变量名传递给标签,并从呈现标签的上下文中获取变量。就像这样:
{% for article in category.articles %}
{% link_to variable: article, text: title %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
在我的代码中(压缩):
def render(context)
uri = "article/#{context[@options[:variable]]['id']}"
"<a href='#{uri}'>#{build_link_text context}</a>"
end
Run Code Online (Sandbox Code Playgroud)
这为我解决了问题context[@markup.strip]。
我的问题是我希望能够将变量传递给自定义的Liquid标签,如下所示: {% get_menu main_menu navigation.html settings.theme.id %}
为了做到这一点,我首先在每个空格字符上将可变字符串拆分为不同的变量。
class GetMenu < Liquid::Tag
include ApplicationHelper
def initialize(tag_name, variables, tokens)
@variables = variables.split(" ")
@menu_object = @variables[0]
@file_name = @variables[1]
@theme_id = @variables[2]
super
end
def render(context)
# This is where i use context[@theme_id.strip] to get the variable of "settings.theme.id"
content = CodeFile.find_by(hierarchy: 'snippet', name: @file_name.to_s, theme_id: context[@theme_id.strip])
@menu ||= Menu.find_by_slug(@menu_object)
context.merge('menu' => @menu)
Liquid::Template.parse(content.code).render(context)
end
end
Liquid::Template.register_tag('get_menu', GetMenu)
Run Code Online (Sandbox Code Playgroud)
*这只是乔纳森·朱利安(Jonathan Julian)上面答案的一个更丰富的例子
| 归档时间: |
|
| 查看次数: |
7467 次 |
| 最近记录: |