The Mijingo Blog

Latest news, updates, free tutorials, and more from Mijingo.

Using Variables in Twig and Craft CMS

by Ryan Irelan

Twig allows us to set variables in our templates so we can repeatedly output a value without calling another method. It also helps make our templates cleaner because a variable can be a shorthand way to reference a value.

There are a few different ways to create and assign values to variables, and they all use the set tag.

The simplest way is like this:

{% set title = "About Happy Lager" %}

by defining the variable name using the set tag and then assigning a value (in this case a string).

This variable can now be used throughout the template using the double curly braces syntax:

{{ title }}

If we had multiple variables to set at once–perhaps some metadata for the page that we wanted to use in multiple places–we can do that by separating both the variables names and their values by commas.

Here’s a simple example:

{% set title, subtitle, description = 'About Happy Lager', 'The history behind the company.', 'Learn more about the history of the this mobile design and development agency.' %}

Each of those variables would then be available in the template, using the double curly brace syntax:

{% set title, subtitle, description = 'About Happy Lager', 'The history behind the company.', 'Learn more about the history of this mobile design and development agency.' %}

<html>
 <head>
  <title>{{ title }}</title>
  <meta name="description" content="{{ description }}">
 </head>
 <body>
  <h1>{{ title }}</h1>
  <h2>{{ subtitle }}</h2>
  <p class="description">{{ description }}</p>
 </body>
</html>

One last way of setting variables in Twig also uses the set tag but instead of as a single tag, we use it as a tag pair. Using it as a tag pair allows us to capture a block of text or code and assign it to the variable. This is handy for assigning a chunk of markup and content to a variable.

{% set description_formatted %}
    <p class="description>Learn more about the history of this mobile design company.</p>
{% endset %}

And that is the basic usage of variables in Twig and Craft CMS.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Filed Under: Craft CMS, Twig