Shopify / liquid

Liquid markup language. Safe, customer facing template language for flexible web apps.
https://shopify.github.io/liquid/
MIT License
10.98k stars 1.38k forks source link

Using liquid class libraries inside Liquid::Tag #671

Open vwochnik opened 8 years ago

vwochnik commented 8 years ago

I've written a liquid tag that makes use of Liquid::Parser and Liquid::Expression although not on the official documentation page. I just wanted to check back and ask if that is reasonably sustainable or the code is going to change soon.

Here's a code excerpt:

class ExampleTag < Liquid::Tag
  def initialize(tag_name, markup, tokens)
    super
    @markup = markup
  end

  def render(context)
    p = Liquid::Parser.new(@markup)
    name = Liquid::Expression.parse(exp = p.expression)
    key = context.evaluate(name)
    raise Liquid::SyntaxError.new("Invalid example tag expression: #{exp}") if key.nil?

    # do something with evaluated key

    # loop through arguments, optionally
    if p.consume?(:colon)
      loop do
        arg = Liquid::Expression.parse(exp = p.expression)
        argstr = context.evaluate(arg)
        raise Liquid::SyntaxError.new("Invalid parameter expression: #{exp}") if argstr.nil?
        # do something with parameter
        break if !p.consume?(:comma)
      end
    end

    # do something more, return
  end
end

At this point, I'm not an expert of liquid. What I want to achieve is parametrical expression parsing within a tag. So for example {% xt 'mandatory expression': 'arg1', 'arg2', variable3 %}.

fw42 commented 8 years ago

Seems a bit weird to parse things during the render step

vwochnik commented 8 years ago

That is true. I could put that part into a parse method but do you suggest I parse inside initialize or is there another possibility?

pushrax commented 8 years ago

Using initialize is the correct way. Feel free to use Liquid::Parser and Liquid::Expression. This is related to https://github.com/Shopify/liquid/issues/560 as well, which would make this experience a lot easier.