【问题标题】:How to pass a variable into a custom tag in Liquid?如何将变量传递给 Liquid 中的自定义标签?
【发布时间】:2011-12-01 17:56:51
【问题描述】:

我在 Liquid 中编写了一个自定义标签,我想将一个变量传递给它。液体标签会将任何参数转换为字符串。

例如:

{% nav page /some/url.html %}

其中 page 是一个变量。

有没有办法让 Liquid 将页面视为变量而不是字符串?

提前致谢!

【问题讨论】:

标签: liquid


【解决方案1】:

如果你专门使用 Jekyll,你可以通过这种方式访问​​页面变量:

def render(context)
  page_url = context.environments.first["page"]["url"]

【讨论】:

  • 好的,我可以通过这种方式访问​​帖子的流动哈希。有没有办法从context 访问Post 对象?
  • 这真的应该进入 Jekyll 文档!
【解决方案2】:

我遇到了类似的问题。我通过创建自定义查找方法解决了这个问题:

def look_up(context, name)
  lookup = context

  name.split(".").each do |value|
    lookup = lookup[value]
  end

  lookup
end

要使用它,请创建如下内容:

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

def render(context)
  output = super
  if @markup =~ /([\w]+(\.[\w]+)*)/i
    @myvalue = look_up(context, $1)
  end

  do_something_with(@myvalue)
end 

【讨论】:

    【解决方案3】:

    要回答一般问题而不是专门关于页面变量的部分,您还可以再次通过 Liquid 解析器传递标签的内容:

    def initialize(tag_name, markup, tokens)
      @markup = markup
      super
    end
    
    def render(context)
      content = Liquid::Template.parse(@markup).render context
    end
    

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2018-04-04
      • 2018-08-03
      相关资源
      最近更新 更多