12
votes

Right now it seems variables I create can't communicate across files.

3

3 Answers

6
votes

For Liquid you can pass a variable in the include

{%- assign global_var = "VALUE" -%}
{%- include 'YOUR_FILE' global_var: global_var  -%}

For Shopify liquid you can do the following:

There is a work around this, you can set the global variable in the theme settings as an option config/settings_schema.json

  {
    "type": "text",
    "id": "global_variable",
    "label": "global variable",
    "default": "Variable value"
  },

and you can access it in the liquid files through

settings.global_variable

But the value is depending on what you enter in the theme settings.

If you need more dynamic way, you can set cart attributes through ajax like:

    $.ajax({
      type: 'POST',
      url: '/cart/update.js',
      data: { attributes: {'global_variable': "MY_VALUE"} },
      dataType: 'json',
      success: function(cart) {
        location.reload();
      }
    });

And then access it any where in the theme through cart.attributes.global_variable But you have to update it each time the cart is empty

5
votes

It seems the templates are loaded before the theme, so variables set in your layout/theme file wont be present in templates. Frustrating. However you can set them via a snippet, and include this snippet in your templates, layout, etc

0
votes

As long as you use the

{% assign variable = value %}

you should be able to get the value anywhere in the file, and any file included after it has been assigned.

I believe this is the closest you can get to global variables in it.