Output: {{ … }}
Base tag: {% … %}
Comments: {# … #}
Array: ['hello', 'world', 3]
Hash: {'name': 'Tyrion', 'age': 5}
Sets a variable value: {% set name = 'Tyrion' %}
Append or merge Strings or arrays:
{% set foo = 'Hello ' ~ name %}
{% set foo = foo|merge(bar) %}
Setting a default vale if foo is not previously defined
{% set foo = foo|default('var is not defined') %}
Simple include:
{% include '_header.twig' %}
Inlcude with custom vars:
{% set headerVars = {'title': 'Homepage'} %}
{% include '_header.twig' with headerVars %}
More: Including other templates
{# layout.html #}
Hello: {% block name %}Annonymous{% endblock %}
{# user.html #}
{% extends "layout.html" %}
{% block name %}Tyrion{% endblock %}
More: Template inheritance
{# _macros.twig #}
{% macro foo(var) %}
Foo and {{ var }}
{% endmacro %}
If you've defined the macros in the same file, you need to import them, using _self: {% import _self as macro %}
{# mytemplate.twig #}
{% import '_macros.twig' as m %}
{{ m.foo('bar') }}
More: Macros in Twig docs
{% if kenny.sick %}
Kenny is sick.
{% elseif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
More: If in Twig docs
{% for u in users %}
{{ u.name }}
{% else %}
No active users.
{% endfor %}
With a conditional:
{% for u in users if u.active %}
With a filter:
{% for u in users|sort('name') %}
More: For in Twig docs