0%

Variables ID: DBT-TPL-VAR

Put simply, variables are chunks of data that may be defined, utilized, and output from templates. It is nearly impossible to create a truly dynamic website without using variables, and complex websites may have hundreds or even thousands of variables.

How variables are defined and utilized can make a developers job simple or painfully complex. So as we define the way Marketpath CMS utilizes variables, we will also provide some tips for making your life as a developer easier.

Defining variables

There are three basic tags that you may use to define variables - the {% var %} tag, the {% set %} tag, and the {% assign %} tag. At their simplest, they may be used to store a simple piece of data for later retrieval.

{% var max = 10 %}

When combined with filters, the variable data may be modified even more before being stored.

There are numerous additional methods that you may use to retrieve data from Marketpath CMS into variables - such as the {% article %} method, the {% blog_posts %} method, the {% images %} method, the {% image_url %} method, and more. For more information on how to use those methods, refer to Marketpath CMS liquid documentation.

{% article var my_article = "About Us" %}

Scope

In all cases, variables are limited to a specific scope. Variables are accessible on the scope in which they are defined as well as any child scopes, unless that same variable is redefined on a child scope by the var tag.

var

var defines a variable for the current scope or child scopes. In the following example, the my_object variable can be used within the if statement but not outside of it.

{% if some_var == "value1" %}
  {% var my_object = "Hello World"%}
  <div>{{ my_object }}</div>
{% endif %}

<div>{{ my_object }}</div> <!-- my_object is not accessible here -->

Additionally, if var is used within a partial template, it will not be available in the parent template that uses the partial.

set

set changes a variable already defined in the current scope. If one is not defined in the current scope, it will move its way up the chain until it finds one. If none is found, the variable is defined on the root scope.

assign

assign defines the variable on the root scope.

 

When working with 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.

Utilizing variables

Using a variable in your templates is generally as simple as typing the variable name.

{% var max = 10 %}
{% blog_posts posts = limit:max %}

Depending on the type of object or data saved in the variable, you may be able to access specific object properties

{% var number_of_posts = posts.total_count %}

{{ request.query_params['first-name'] }}

You may also utilize variables as arguments for filters.

{% set page_title = entity.browser_title | truncate:max %}

Some tags allow you to utilize filters directly, while others do not. This will be specified in each individual method definition.

{% set_description entity.meta_description | default: site.default_meta_description %}

If the tag allows it, utilizing the filters directly in the tag may make your code more readable, but only if you do not also need to use the same value later in your code.

If in doubt, the best practice is to define a new variable whenever you need to alter the information stored in an existing variable. This will preserve the value stored in the original variable while allowing either the new or old value to be used later in the code. It also typically leads to cleaner templates, particularly if your variables have appropriately descriptive names.

Outputting Variables

Outputting a variable is nearly the simplest thing you can do with a template. All you have to do is surround the variable with {{ and }} characters. That's it! 

{{ entity.title }}

You may also use filters when you output variables and may access object properties as described above.

Debugging Variables

While authoring templates, it can often be helpful to know what is currently stored in a variable so that you can decide what type of code to write - or why your code does not output what you expected it to output. To assist with this, you should use the inspect filter.

{{ entity | inspect: 5 }}

While this is an incredibly helpful filter, we recommend that you do not publish any templates with this filter in use. Instead, just save the template and use the preview site for debugging. Remove the filter as soon as you are done with it. This will help keep both your code and your output clean.

Reference Variables

There are occasional instances where you need more from your variables. You need them to be even more dynamic - you need to store and retrieve values by reference! Not all tags and filters support passing by reference, so you will have to refer to the documentation when determining if this is even possible, but there are a number of places where you may add a '&' in front of an argument in order to store or retrieve a value by reference.

This is a little complicated. Maybe an example would be more helpful:

{% var customheader = 'x-custom-header-denied' %}
{% if test_passed %}
  {% set customheader = 'x-custom-header-allowed' %}
{% endif %}
{% set_header &customheader:session.id %}

As you can see from this example, the header that is set will depend on whether or not test_passed is true.

In the following more complicated example, you may retrieve a collection of blog posts filtered by the current entity. If the current entity is a 'blog', it will return the three most recent blog posts from the current blog. If it is a 'tag', it will return the three most recent blog posts with the tag. If it is an 'author', it will return the three most recent blog posts with the author, etc... If it is an unsupported entity type (eg: form), it will simply return the three most recent blog posts from the site:

{% blog_posts var posts = &entity.object_type:entity limit:3 sort_by:'post_date' sort_direction:'desc' %}

Variable Arguments Syntax

In some cases you may want to use the same method with different arguments - and a different number of arguments - depending on other factors. The most straightforward way to do this is to use {% if %} and {% unless %} methods for each possible combinations. However, if there are many possible combinations this may be impractical or impossible to do - in which case you may prefer to use a variable argument. Not all methods support the variable arugment but most methods that accept multiple arguments do.

A variable argument is simply the name of a variable prefixed by '*'. This instructs the method to extract the method arguments from the referenced variable. In addition, the referenced variable may also include other variables by reference (see the above &variable syntax for further information):

{% capture filters -%}
  {% if blog_filter is_valid %}blog_post:{{blog_filter}}{% endif %}
  {% if tag_filter is_valid %}tag:{{tag_filter}}{% endif %}
  {% if author_filter is_valid %}author:{{author_filter}}{% endif %}
  {% if other_filter_var is_valid and other_filter_val is_valid %}&other_filter_var:other_filter_val{% endif %}
  {% if custom_sort %}{{custom_sort}}{% else %}sort_by:'post_date' sort_direction:'desc'{% endif %}
{%- endcapture %}
{% blog_posts posts = *filters start:1 limit:10 %}

Variable Names

As a rule, variable names may only contain upper and lower-case characters, number, dashes, and underscores. Variable names are case-sensitive. 

When defining variables, the best practice is to define a clear naming convention and stick with it, and to use variable names that are as descriptive as possible. One of the most popular naming convention is to write all of your varaible names in lower-case with underscores between words. This will make your code more readable and more maintainable. Marketpath CMS sets your custom field names this way by default.

Try not to re-use variable names where possible, unless it makes sense under the current scope. Examples of variable names that are likely to be re-used in different scopes are:

  • start
  • limit
  • posts
  • post
  • items
  • item
  • entry
  • collection
  • date
  • etc..

If you need to re-use a variable in a different scope (eg: you want to re-use it in both the header and footer), consider prefixing your variable name with a "unique" prefix (eg: ccr_page_collection). This slightly reduces readability but makes it much less likely that another developer assigns something different to your variable.

The following varaible names are reserved and may not be defined as a new variable, including when assigning by reference:

  • auth
  • automatic_markup
  • body_tags
  • client
  • client_permissions
  • cookies
  • entity
  • header_tags
  • mp_editor_preview
  • page
  • profile
  • request
  • session
  • site
  • SiteGUID


Feedback?

Please fill out the form below with your feedback or any questions you may have after working through the "Variables" lesson.

Your Name
Email 
Feedback / Questions