Liquid Variable Scope Between Layout And Template

- 1 answer

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?



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.