Variables
- Simple variable
- <h1>{{ sitename }}</h1>
- Array element (value of key name in array named user)
- <h2>{{ user.name }}</h2>
- Always available variables:
- {{ _context }} - current context
- {{ _self }} - current template
- {{ _charset }} - current character set
Assignments
Use set tag:
- a simple value
- {% set foo = ‘bar’ %}
- an array
- {% set foo = [1,2] %}
- array with keys
- {% set foo = {’foo’:’bar’} %}
- with a variable
- {% set foo = bar ~’baz’ %}
- longer strings
- {% set message %}
This is an error message.
{% endset %}
Control structures
- Available:
- if (same as in PHP), elseif, else, for, tags (see below)
- {% for user in users %}
<li>{{ user.username }}</li>
{% endfor %}
- Expressions
- or, and, ==, !=, <, >, >=, <=, in, +, -, ~, *, /, %, //, is, .., **
Tag
- Must have start and end tag
- {% if page is defined %}
<h1>{{ pagetitle }}</h1>
{% endif %}
Filter
- Apply one or more separated by a pipe (|)
- {{ list|join(‘, ‘)|title }}
Escaping
- To escape Twig specific tags use raw filter
- {{ '{{twigvariable}}'| raw }}
- To escape HTML use escape filter (PHP’s htmlspecialchars())
- {{'<script>iCanHasServer(?)</script>' | escape}}
Includes
- Simple Include
- {% include 'relative/to/template/root/mypage.html' %}
- Pass vars to the included file as an object
- {% include 'mypage.html' with {'key': 'value'} %}
Block
- Lorem ipsum dolor sit amet, consectetur adipisicing elit,
- {{ sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. }}
- Lorem ipsum dolor sit amet, consectetur adipisicing elit,
- {{ sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. }}
- Lorem ipsum dolor sit amet, consectetur adipisicing elit,
- {{ sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. }}
Macros
- Twig macro == PHP function (no access to variables outside of the macro).
- {% macro state_option(code, name, current) %}
{% set selected = current == code ? 'selected' : '' %}
<option value="{{code}}" name="{{name}}" {{selected}}>{{name}}</option>
{% endmacro %}
- Can be defined anywhere but needs to be imported before use.
- {% import "states-select.html" as states %}
- Calling macros
- {{ states.state_option(state.code, state.name, selected_state) }}
Translation
Uses Twig i18n plugin
- Use short version for simple strings without variables and double quotes
- {%trans “Hello world!” %}
- Use long version for more complex strings. All variables must be simple variables.
- {% trans %}
Hello {{user.name}}
{% endtrans %}
- Translation with a placeholder and a filter
- {% set message %}
{% trans "Sorry! We can't find %loc. Please try again." %}
{% endset %}
{{ message | replace({'%loc': search}) }}