Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Liquid variable scope between Layout and Template

Tags:

shopify

liquid

Is is possible to define liquid variables in a layout file that are visible in the template files?

Variables defined in a layout (e.g. theme.liquid) are visible to any snippets included via <% include %> (and vice versa).

Variables defined in a template (e.g. index.liquid) are visible in any snippets included via <% include %> (e.g. product-grid-item.liquid) and are also visible in the layout file.

And yet variables defined in a layout don't seem to be visible to the template. Presumably the template is evaluated prior to the evaluation of the layout. Is there any way to override this behavior?

like image 588
hendalst Avatar asked Aug 16 '16 14:08

hendalst


1 Answers

Currently in Shopify, Liquid variables cannot be passed from the layout into the template.

One way to get around this would be to do the same logic twice, perhaps in a snippet. Then place the same snippet in both the Layout and the template.

Also worth noting on the subject of Shopify Liquid scope as it isn't documented anywhere is that variables defined inside of sections are scoped inside of that section and cannot be access outside.

EDIT: Also on the subject of Shopify Liquid variable scope. There is now also the {% render %} tag which forces a snippet to be called with the required variables explicitly passed in.

For example you could do this with include

{% assign name = 'cart' %}
{% include 'icon' %}

Alternatively, you can use the render tag which has some performance benefits. Just ensure you explicitly pass the name variable.

{% render 'icon' name: 'cart' %}

<!-- OR -->

{% assign name = 'cart' %}
{% render 'icon' name: name %}

The benefit of using render is that the variables are always scoped to the snippet which can prevent some confusing bugs. Additional there is a big speed performance on Shopify's server which will improve the Time to First Byte.

like image 80
GeorgeButter Avatar answered Oct 22 '22 10:10

GeorgeButter