/awesome-twig

A collection of useful Twig snippets.

Awesome Twig

A curated list of useful Twig snippets.

If you want to contribute, you are highly encouraged to do so :)

Table of Contents

Array, Mapping, and String

Concatenate Data

{{ 'Name: ' ~ user.name }}

First and Last Elements of an Array (or mapping, or string)

{{ todoList|first }}

{{ todoList|last }}

[1] [2]

Limit the Length of a Text and Add Ellipsis

{{ text|length > 50 ? text|slice(0, 50) ~ '...' : text }}

or using the Twig Extension truncate:

{{ text|truncate(50, true) }}

[1]

Date and Time

Current Date

{{ "now"|date("d/m/Y") }}

Internationalization

[1]

Display Localized Date

{{ post.published_at|localizeddate('medium', 'none', locale) }}

Display Localized Currency Value

{{ price|localizedcurrency('BRL') }}

Display Localized Number

{{ product.quantity|localizednumber }}

Loop

Filter Values Before Using them in a Loop

{% for item in posts if item.published %}
    ...
{% else %}
    There are no items.
{% endfor %}

Using the Keys of an Array

{% for key in array|keys %}
    ...
{% endfor %}

Misc

Named Arguments for Filters

{{ someVariable|convert_encoding(from='ISO-8859-1', to='UTF-8') }}

Structure

Check If a Block Exists in Current Template

{% if block("footer") is defined %}
    ...
{% endif %}

{% if block("footer", "common_blocks.twig") is defined %}
    ...
{% endif %}

Template

Fallback Templates

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

Loading a Template From a String

{{ include(template_from_string("Welcome {{ name }}")) }}

[1]

URL

Generate URL-encoded Query String

{{ {'param': 'value', 'foo': 'bar'}|url_encode }}
{# outputs "param=value&foo=bar" #}

[1]

Variable

Check If a Variable is Defined

{% if someVariable is defined %}
    ...
{% endif %}

Check for Empty Variable

Check if is not null, empty, or zero, and add a default value (if the variable is not defined)

{% if someVariable|default('someValue') %}
    ...
{% endif %}

Using a Default Value If a Variable is not Defined

{{ name|default('John Smith') }}