User Guides

Twig Basics

This page outlines a few of the core concepts around using Twig, for full documentation we recommend reading the official Twig documentation.


Introduction

Twig is an easy to understand templating language written specifically for designers.

In Twig, there are two kinds of delimiters, those are {{ ... }} and {% ... %}. The first one is responsible for printing the results of an expression into a template whereas the second is used to execute statements such as if-statements and for-loops.


Variables

Variables can be printed to a template as follows:

{{ foo }}

If the variable is an array or an object, the keys or properties of the variable can also be accessed like so:

{{ foo['bar'] }}
{{ for.bar }}

Loop Tags

Loops can be used to iterate through any iterable content, for example an array of blog posts.

{% for post in blogPosts %}
  {{ post.title }}
{% endfor %}

Logic Tags

Logic tags can be used in your templates in order to create conditional content, the example below demonstrates how you could display a list of blog posts only if any blog posts actually existed. If there are no blog posts, a message will be displayed.

{% if blogPosts|length > 0 %}

  {% for post in blogPosts %}
    {{ post.title }}
  {% endfor %}

{% else %}

  No blog posts found!

{% endif %}

Filters

Filters allow you to modify content from within your template, they are used by simply inserting a pipe ( | ) followed by the name of the filter you would like to apply.

{{ foo|striptags }}

Filters can also be chained, allowing you to modify data multiple times.

{{ foo|striptags|capitalize }}

For a list of all available filters, please see the Twig documentation


Functions

Functions are used to generate content, they are called by their name followed by a set of parentheses ( () ) and may also have arguments.

The example below prints out a comma separated list of the numbers 0 to 3.

{% for i in range(0, 3) %}
  {{ i }},
{% endfor %}

For a list of all available functions, please see the Twig documentation


Comments

Comments allow you to enter snippets of text into your templates that will not be evaluated or printed.

{# This line will not be printed #}

Further Reading

You can find more information about using Twig using the links below:

  • Twig for Template Designers goes into a good amount of detail about each of Twig's features.
  • The Twig Reference provides an overview of each of the tags, filters, functions and operators available in Twig templates.