2011-10-27 54 views
15

內液體變量我在液體做了一個自定義鏈接標籤,我想能夠液體變量傳遞到調用該標籤,像這樣使用液體標籤調用

{{ assign id = 'something' }} // this value is actual dynamic while looping through data 
{% link_to article: id, text: 'Click Me!' %} // my custom tag 

然而,這導致文章參數按照'id'而不是'something'按照上面的assign語句傳入。

有誰知道如何將變量傳遞給標記調用?

回答

2

看起來不像這是可能的,我的解決辦法是隻在該標籤傳遞的變量名稱,並抓住它的標籤正在被渲染的背景下,像這樣:

{% for article in category.articles %} 
    {% link_to variable: article, text: title %} 
{% endfor %} 

在我的標記代碼(濃縮):

def render(context) 
    uri = "article/#{context[@options[:variable]]['id']}" 
    "<a href='#{uri}'>#{build_link_text context}</a>" 
end 
+0

你怎麼測試呢? – mhenrixon

5

我最近被作爲標籤參數傳遞變量的解決了這個非常簡單地傑基爾0.11.2和液體2.3.0。

{% assign v = 'art' %} 
{% link_to_article v %} 

您也可以在循環中傳遞控制變量的名稱,例如上面的article

Liquid::Tag.initialize@markup是第二個參數,標籤名稱後面的字符串。分配的變量可在context的頂層獲得。

def render(context) 
    "/#{context[@markup.strip]}/" 
end 

這顯然只允許一個參數傳遞。更復雜的解決方案將解析像x: 2, y: 3這樣的參數。

3

這解決了我的情況context[@markup.strip]

我的問題是,我希望能夠給一個變量傳遞給我的自定義標籤的液體像這樣:{% get_menu main_menu navigation.html settings.theme.id %}

爲了做到這一點,我首先拆分變量字符串轉換成不同的varaibles上的每個空格字符。

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) 

*這僅僅是一個更豐富的實例,通過喬納森·朱利安

0

上面的答案這將是巨大的,有一個可以用文字和變量被稱爲像

{% assign v = 'art' %} 
{% link_to_article v %} 

標籤或

{% link_to_article 'art' %} 

{% link_to_article "art" %} 

,也當然

{% link_to_article include.article %} 

爲了讓我提出一個輔助函數

def get_value(context, expression) 
    if (expression[0]=='"' and expression[-1]=='"') or (expression[0]=="'" and expression[-1]=="'") 
    # it is a literal 
    return expression[1..-2] 
    else 
    # it is a variable 
    lookup_path = expression.split('.') 
    result = context 
    puts lookup_path 
    lookup_path.each do |variable| 
     result = result[variable] if result 
    end 
    return result 
    end 
end 

而且在渲染只需調用輔助函數來獲取文字或變量的值。

def render(context) 
    v = get_value(context, @markup.strip) 
end 

僅供參考,初始化劑是這樣的:

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