Base Syntax

Output: {{ … }}
Base tag: {% … %}
Comments: {# … #}
Array: ['hello', 'world', 3]
Hash: {'name': 'Tyrion', 'age': 5}

Setting Variables

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') %}

Including other Templates

Simple include:
{% include '_header.twig' %}

Inlcude with custom vars:
{% set headerVars = {'title': 'Homepage'} %}
{% include '_header.twig' with headerVars %}

More: Including other templates

Blocks and extending Templates

{# layout.html #}
Hello: {% block name %}Annonymous{% endblock %}
  
{# user.html #}
{% extends "layout.html" %}

{% block name %}Tyrion{% endblock %}

More: Template inheritance

Macros

{# _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

Simple "If/Else" control

{% 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

Simple "For" control

{% 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

Hire me!

I'm currently open for new projects or join pretty much any project i may fit in, let me know!

Read about what I do, or contact me for details.

Categories