using Liquid variables inside of a liquid tag call

后端 未结 4 977
鱼传尺愫
鱼传尺愫 2020-12-01 21:08

I made a custom link tag in Liquid and I am trying to be able to pass liquid variables into the call for that tag like so

{{ assign id = \'something\' }} //          


        
4条回答
  •  一生所求
    2020-12-01 21:36

    It would be great to have a tag that can be called with literals and variables like

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

    or

    {% link_to_article 'art' %}
    

    or

    {% link_to_article "art" %}
    

    and also of course

    {% link_to_article include.article %}
    

    In order to so I propose a helper function

    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
    

    And in the render just call the helper function to get the value of the literal or variable.

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

    FYI, the initialiser would look like this:

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

提交回复
热议问题