Search code examples
variablesshopifyliquid

Can't access variable defined in Snippet from Template in Liquid


I have a snippet that is included in multiple templates. It performs some operations and then defines a few variables with values based on the results of those operations. The templates then need to use those those values in a couple different ways.

It seems that I cannot access a variables defined in the snippet from the templates. A VERY watered down example:

Sinppets/colors.liquid

{% assign myVar = "bar" %}

templates/color-picker.liquid

{% assign myVar = "foo" %}
{% render 'colors' %}
{{ myVar }}

The output of this is foo while the expected output is bar.

Am I doing something wrong, or is this just not possible?


Solution

  • You're not doing anything wrong, and yes, it's just not possible, at least not with render.

    Variables declared inside of snippets called by render are only accessible inside of that snippet. Render has replaced include which is now deprecated, but allowed you to achieve what you are trying to do in the example above.

    That said, you can still use include for now - more info here >> https://shopify.dev/api/liquid/tags/deprecated-tags#include