-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Get all variables used in a template #685
Comments
Not that I know of, no. Sorry :( |
You could add some hooks to the variable lookup function if you are ok with running a custom liquid version. |
Hi, is there a solution for this yet? I'd also like to find all variables used in a template. Thank you. |
No solution, sorry. And nothing planned so far. But I'm open to look at suggestions. |
Somewhat hacky, but I put together this for my use case: def get_variables(t)
variables = []
nodes = Liquid::Template.parse(t).root.nodelist
nodes.each do |n|
variables << n.name.name if n.is_a? Liquid::Variable
end #End loop
#Return
variables.uniq
end #End method
>> get_variables("{{friend}} is such a {{animal}}")
>> ["friend", "animal"] Not even sure if this is ok. What do you think? :D Edit: (You know what I did) |
Assuming you only care about top level variables that will work. You also need to check that |
Wow, I didn't know that you could have variables like that. Thanks for the suggestion, thanks! |
If you export all your variables using Liquid::Drop, you can run your liquid template against mock liquid drop with same methods as the usual liquid drop, but registering what variables were used. |
With #1025 being available in 4.0.2 this can now be achieved using the following code Liquid::ParseTreeVisitor.for(Liquid::Template.parse(liquid_string).root).add_callback_for(Liquid::VariableLookup) do |node|
[node.name, *node.lookups].join('.')
end.visit.flatten.compact |
liquid_string = "Hi {{ email }}"
vars = Liquid::Template
.parse(liquid_string)
.root
.nodelist
.select { _1.is_a? Liquid::Variable }
.map(&:name)
.map(&:name)
.uniq
vars # => ["email"] |
what would be the best way to filter out variables from for loops? Currently if i run this for a template that includes a loop it retrieves the variable used to iterate over the collection, for example: {% for order in orders %}
{{ order.id }}
{% endfor %} as a result I get |
@fer9305 I'm also interested in this. Did you find a way to filter them out? |
Hi,
Is there a way of finding out all variables being used in a template, or at least the ones that it couldn't replace when rendering the template? Both, the ones used as
{{ name }}
and also the ones used in other tags{% if name == 'John' %}
Thanks :)
The text was updated successfully, but these errors were encountered: