A curated list of useful Twig snippets.
If you want to contribute, you are highly encouraged to do so :)
- Array, Mapping, and String
- Date and Time
- Internationalization
- Loop
- Misc
- Structure
- Template
- URL
- Variable
{{ 'Name: ' ~ user.name }}
{{ todoList|first }}
{{ todoList|last }}
{{ text|length > 50 ? text|slice(0, 50) ~ '...' : text }}
or using the Twig Extension truncate
:
{{ text|truncate(50, true) }}
{{ "now"|date("d/m/Y") }}
{{ post.published_at|localizeddate('medium', 'none', locale) }}
{{ price|localizedcurrency('BRL') }}
{{ product.quantity|localizednumber }}
{% for item in posts if item.published %}
...
{% else %}
There are no items.
{% endfor %}
{% for key in array|keys %}
...
{% endfor %}
{{ someVariable|convert_encoding(from='ISO-8859-1', to='UTF-8') }}
{% if block("footer") is defined %}
...
{% endif %}
{% if block("footer", "common_blocks.twig") is defined %}
...
{% endif %}
Include the first template that exists:
{{ include([
'sites/' ~ site.slug ~ '/main.twig',
'sites/' ~ site.slug ~ '/default.twig',
'common/site_main.twig'
]) }}
or ignore if template is missing:
{{ include('sites/' ~ site.name ~ '/main.twig', ignore_missing=true) }}
{{ include(template_from_string("Welcome {{ name }}")) }}
{{ {'param': 'value', 'foo': 'bar'}|url_encode }}
{# outputs "param=value&foo=bar" #}
{% if someVariable is defined %}
...
{% endif %}
Check if is not null, empty, or zero, and add a default value (if the variable is not defined)
{% if someVariable|default('someValue') %}
...
{% endif %}
{{ name|default('John Smith') }}