Home | About Me
| | | | | | | | | |

Symfony 3:[Twig]: Reference

Hands-On | 18 Aug 2018
Tags: twig, symfony, ready, template, filter, twig-inheritance, for-loop, twig-filter


Template file name

[template_name].html.twig
{# comment #}

Template block

{% block [block_name] %}
    [block_content]
{% endblock %}

Extending twig template

{% extends [template_name] %}

Output a variable

{{ [variable_name] }}

For loop

{% for post in posts %}
  {{ post.title }}: {{ post.text }}
{% endfor %}

Generate URL from annotated route name

{{ path([route_name]) }}

Twig Filters

Uppercase conversion:
{{ post.title|upper }}

Date conversion:
{{ post.data|date('H:i:s') }}

Environment variables

{{ app.environment }}
{{ app.user }}
{{ app.request }}
{{ app.session.isStarted() }}
{{ app.debug }}

Example: Extending Twig - Creating Filter

The price filter added above will be used as:

{{ 1029|price }}

Extension is automatically configured and 'twig.extension' tag is added based on inheritance from AbstractExtension class (and autoconfigure: true in services.yaml)

Global Variables in Twig

# config/packages/twig.yaml
twig:
    paths: ['%kernel.project_dir%/templates']
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    globals:
      message: '%hello_message%'

Here %hello_message% is defined as parameter in services.yaml and is not available as global variable "message" within twig templates.

. number_format($number, 2, '.', ','); } } 

The price filter added above will be used as:


Extension is automatically configured and 'twig.extension' tag is added based on inheritance from AbstractExtension class (and autoconfigure: true in services.yaml)

Global Variables in Twig


Here %hello_message% is defined as parameter in services.yaml and is not available as global variable "message" within twig templates.