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 }}
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getFilters()
{
return [
new TwigFilter('price', [$this, 'priceFilter'])
];
}
public function priceFilter($number)
{
return '
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.