Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define global variables in Liquid?

Tags:

shopify

liquid

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

like image 868
Austin Bravo Avatar asked Jan 29 '16 22:01

Austin Bravo


People also ask

How do you define a global variable?

Global variables, as the name implies, are variables that are accessible globally, or everywhere throughout the program. Once declared, they remain in memory throughout the runtime of the program. This means that they can be changed by any function at any point and may affect the program as a whole.

Where do you declare global type variables?

Hence, the natural place to put global variable declaration statements is before any function definitions: i.e., right at the beginning of the program.

Can we declare global variable?

You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.


2 Answers

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

like image 127
Hussam Kurd Avatar answered Sep 27 '22 16:09

Hussam Kurd


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

like image 37
Anthony Manning-Franklin Avatar answered Sep 27 '22 18:09

Anthony Manning-Franklin