Templating Basics

The best place to begin to learn twig is by reading the actual twig documentation.

See:

Below we will give some examples of the most basic concepts you should understand before diving in, but before that there are three key syntaxes you should be aware of:

  • {{ }} - Double curly braces are used for outputting/printing.

  • {% %} - Single curly brace followed by percent symbol is used for manipulation and logic.

  • {# #} - Single curly brace followed by a pound symbol is used for commenting in your templates. Twig will act as if they don't exist.

With that knowledge, lets dive in.

Variables#

Variables in twig can store a variety of different types of values, just like in other programming languages, theres strings, arrays, booleans, objects, and null values. Variables can be created, manipulated, printed, and passed to functions or filters.

Your templates come pre-loaded with a few global variables, which you can read about here.

Set a variable

{% set welcome = 'Welcome to my website!' %}

Print a variable

{{ welcome }}

Functions#

Functions usually take a input variable and manipulate it in some way

{% set fruit = ['apple', 'pear', 'lemon'] %}

{{ random(fruit) }}

See also:

Filters#

Filters provide information about, or manipulate a variable. They are used by chaining pipes |

{% set colors = ['blue', 'red',' yellow'] %}

{{ colors|length }}

{{ 'johnny'|capitalize }}

{{ 'redrum'|reverse }}

See also:

Tags#

Tags allow for flow control in your templates

{% for x in range(0,10) %}

    {{ x }},

{% endfor %}


{% if 'now'|date('Y') == 2016 %}

     <div>It's 2016!!!</div>

{% else %}

    <div>What year is it then???</div>

{% endif %}


{% include 'header.html' %}

See also:

Tests#

Test a condition returning a boolean true or false

<ul>

{% if num in range(0,10) %}

    <li class='{% if num is even %}even{% else %}odd{% endif %}'>

        {{ num }}

    </li>

{% endif %}

</ul>

See also:

Operators#

Constructs which behave generally like functions, but which differ syntactically or semantically from usual functions. Common simple examples include arithmetic (addition with +, comparison with >) and logical operations (such as AND or &&). More involved examples include assignment (usually = or :=)

{% set num = 10 + 15 * 3.5 / 4 %}


{% set message = 'Hi, my name is ' %}

{% set message = message ~ 'Johnny Smith' %}


{% if '10' === 10 %}

{% endif %}

See also:

  • in

  • is

  • Math (+, -, /, %, //, *, **)

  • Logic (and, or, not, (), b-and, b-xor, b-or)

  • Comparisons (==, !=, <, >, >=, <=, ===,starts with, ends with, matches)

  • Others (.., |, ~, ., [], ?:)