How to pass a variable into a custom tag in Liquid?

回眸只為那壹抹淺笑 提交于 2019-12-21 07:20:54

问题


I have written a custom tag in liquid, and I'd like to pass a variable to it. Liquid tags will turn any parameter into a string.

For example:

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

Where page is a variable.

Is there a way to get Liquid to treat page as a variable and not a string?

Thanks in advance!


回答1:


If you are using Jekyll specifically, you can access the page variable this way:

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



回答2:


I had a similar problem. I solved it by creating a custom lookup method:

def look_up(context, name)
  lookup = context

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

  lookup
end

To use it, create something like this:

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:


To answer the general question and not the part specifically about the page variable, you can also pass the contents of the tag through the Liquid parser again:

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

def render(context)
  content = Liquid::Template.parse(@markup).render context
end


来源:https://stackoverflow.com/questions/7666236/how-to-pass-a-variable-into-a-custom-tag-in-liquid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!