Variable Scopes

Variable Scopes

While it is possible to create templates without a good understanding of scope, it may be helpful to understand how liquid variables are scoped in order to create truly reusable template or integrate smoothly with code written by other developers.

By using variable scopes effectively, developers can create and edit intuitive and reusable templates without interfering with functionality implemented by other template developers on the same site. All the developer needs to do is store their objects on the child scope and when their template is done rendering it will not have disturbed any of the parent template objects or variables. For example: you could use the variable "start" even if the same variable is used by a parent template, and when your template is done rendering the "start" object would be unchanged in the parent scope.

There are three different ways to save objects on the scope which are designed to give you full control over where objects are saved without becoming overly complicated:

  • var stores the variable on the current scope. Once the current scope is completed, the variable will no longer be accessible. This is the default functionality for everything except for the {% assign %} and {% set %} methods.
  • set updates the variable on the closest scope which it is already defined on. The the variable has not been defined on any scope, it will be stored on the root scope.
  • assign removes the variable from all scopes and stores it on the root scope.

When writing templates, the best practice is to utilize var and set wherever possible and reserve assign for cases where it is specifically necessary. By restricting your variables to the scopes where they are used, you make your code more friendly and compatible with code written by other developers who may wish to use the same variable names.

Note that there is currently no way to unset a variable from a scope other than using the assign method to define the variable at the root scope. Setting a variable to null does not remove it from the scope.