【问题标题】:Liquid Custom Tag: Block tag with optional closing tag液体自定义标签:带有可选结束标签的块标签
【发布时间】:2013-11-08 20:53:07
【问题描述】:

是否可以创建具有 可选 结束标签的自定义 Liquid::Block 标签?

例如:

{% mytag 'parameter' %}
    <!-- ...Do something... -->
{% endmytag %}

或:

{% mytag 'parameter' %} <!-- Do something else -->

我能找到的与预先存在的示例最接近的是内置的“if”标签,它有时可以在其中包含可选的“else”或“elsif”标签。这是通过覆盖类中的“unknown_tag”方法并通过那里处理“else”和“elsif”标签来实现的。基本上,如果没有找到结束标签,我只需要在模板中自定义标签的位置内联渲染一些内容。否则,我需要获取块的内容并将其替换为不同的内容。

【问题讨论】:

    标签: ruby-on-rails liquid


    【解决方案1】:

    所以,我想我已经解决了这个问题。我确信使用一些内置的、未记录的 Liquid API 可能有更好的方法。但是,这似乎至少适用于我的用例:

    class MyTag < Liquid::Block
      def initialize(tag_name, markup, tokens)
        super
    
        # Other init code here...
      end
    
      def parse(tokens)
        @has_closing_tag = has_closing_tag?(tokens)
    
        super(tokens) if @has_closing_tag
      end
    
      def render(context)
        if @has_closing_tag
          # Handle normal "block" case here...
        else
          # Handle special "tag" case here...
        end
      end
    
      private
        def has_closing_tag?(tokens)
          stack = []
    
          tokens.each do |token|
            next unless token.match(Liquid::TagStart, 0)
    
            tag_name = FullToken.match(token)[1]
    
            stack.push(block_name) if tag_name == block_name
    
            if tag_name == block_delimiter
              return true if stack.size == 0
    
              stack.pop
            end
          end
    
          false
        end
    end
    

    【讨论】:

      猜你喜欢
      • 2016-08-25
      • 1970-01-01
      • 2015-06-11
      • 2016-05-04
      • 2014-12-26
      • 2019-05-21
      • 2015-03-24
      • 2011-01-02
      • 2017-05-13
      相关资源
      最近更新 更多