I'm working on a project which uses the Liquid template language. I have a page with iframes showing some rendered liquid templates and an editor section. In the editor section the user can change the values of some of the variables referred to in the liquid templates. At this point some of the templates need to be re-rendered but I only want to re-render those templates which refer to the variable which has been changed.
The point I'm stuck on is how best to get a list of the variables referred to in a liquid template.
So if I do this:
templates=[]
templates[0] = Liquid::Template.parse("hi {{name}}")
templates[1] = Liquid::Template.parse("my cat is called {{cat_name}}")
I want to know that 'name' is referenced but that (e.g.) 'cat' is not in template 0. Then when name is changed I can re-render template[0] and when cat is changed I can re-render template[1].
I've found that I can get a list of nodes and check each one to see if it is a variable, e.g. templates[0].root.nodelist[1] has a type of 'Liquid::Variable' but the 'name' method of the variable returns an object of type 'Liquid::VariableLookup' which in turn doesn't seem to have a method for getting a name out of it and this feels like I might be going about it the wrong way.
For example, you could build URLs to external tools based on the results of a query, or change which database table is queried based on a user’s selection. Liquid statements are built from variables, filters, and tags. Variables contain information that you want to use, and the variables that Looker provides are described on this page.
Basic usage of Liquid variables is straightforward. Once you’ve identified the variable you’d like to use (see the following list), simply insert it into a valid LookML parameter. The specific Liquid variables that you can use in specific LookML parameters are defined next.
Liquid variables are usually based on the field where they are being used. However, you can also access values from other fields if needed. Use the format {{ view_name.field_name._liquid-variable-name }} to access other fields from the same row in the query result.
LiquidJS syntax is relatively simple. There’re 2 types of markups in LiquidJS: Tags. A tag consists of a tag name and optional arguments wrapped between {% and %}. Outputs. An output consists of a value and a list of filters, which is optional, wrapped between { {` and `}}.
Following https://github.com/Shopify/liquid/issues/685#issuecomment-471499796 you can use FileTreeVisitor
class for that. Namely:
template = Liquid::Template.parse("hi {{name}}")
Liquid::ParseTreeVisitor.for(template.root)
.add_callback_for(Liquid::VariableLookup) do |node|
[node.name, *node.lookups].join('.')
end.visit.flatten.compact # => ["name"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With