Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 62 ยท Templates with Twig

Twig Functions, Filters and Tests

A tour of Twig's built-in filters, functions and tests, plus Symfony's path(), url() and asset() helpers, escaping rules and loops, with a runnable evaluator.

Printing variables gets you only so far. Real templates format prices, join lists, build links to routes, test whether a value is empty or even, and loop over data. Twig covers these jobs with three kinds of building blocks that look different on purpose:

  • Filters transform a value and are written with a pipe: name|upper.
  • Functions produce a value from arguments and are called like functions: range(1, 5).
  • Tests answer yes or no and are written with is: count is even.

This lesson tours the most useful built-ins of each kind, the Symfony-specific helpers path(), url() and asset(), the escaping rules, and the loop variable. You should know Twig Basics and layouts. The runnable examples use a stand-in evaluator; the real syntax is shown in read-only blocks.

Filters you will use every day

A filter receives the value on its left as its first argument; extra arguments go in parentheses. Filters chain from left to right, so name|lower|capitalize lowercases first and then capitalizes.

Group Filters
Text upper, lower, capitalize, title, trim, striptags, nl2br, slice, replace, format, u
Lists length, join, split, first, last, reverse, sort, keys, merge, batch, filter, map, reduce
Numbers round, abs, number_format, format_number, format_currency
Dates date, date_modify, format_date, format_datetime
Safety escape (e), raw, url_encode, json_encode
Fallbacks default

A few worth a closer look:

TWIG
{# real Twig, read-only #}
{{ post.title|slice(0, 40) }}                {# first 40 characters #}
{{ tags|join(', ', ' and ') }}                {# "php, twig and symfony" #}
{{ '%s has %d items'|format(user.name, count) }}
{{ price|number_format(2, '.', ',') }}        {# 1,234.50 #}
{{ post.publishedAt|date('d M Y') }}
{{ products|map(p => p.name)|join(', ') }}    {# arrow functions #}
{{ products|filter(p => p.stock > 0)|length }}

default is the one you will reach for most: {{ user.nickname|default('anonymous') }} supplies a fallback when the value is empty or undefined. The map, filter and reduce filters take arrow functions (p => p.stock > 0), which keeps small data transformations in the template instead of the controller.

The date filter accepts a DateTimeInterface, a timestamp, or a date string. If you build an international site, prefer the Intl filters format_date, format_number and format_currency from the twig/intl-extra package, which respect the visitor's locale.

For longer text transformations use {% apply %} to run a filter over a whole block:

TWIG
{# real Twig, read-only #}
{% apply upper %}
    This whole block becomes uppercase.
{% endapply %}

Functions

Functions are written name(arguments). These Twig built-ins show up constantly:

  • range(1, 5) returns [1, 2, 3, 4, 5] (also range('a', 'e') and a step as a third argument).
  • max(...) and min(...) return the largest and smallest value of their arguments or of a list.
  • cycle(['odd', 'even'], loop.index0) picks alternating values, useful for striped rows.
  • random(...), date('now') and dump(value) are available but non-deterministic or debug-only. dump() works in the dev environment when the VarDumper component is installed.
  • include('file.html.twig') and block('name') render a fragment, as you saw in the layouts lesson.
  • constant('App\\Entity\\Order::STATUS_PAID') reads a PHP constant.

Symfony's helper functions

The TwigBundle and related packages add functions that talk to the framework:

Function What it does
path('route_name', {id: 3}) Relative URL for a route: /products/3
url('route_name', {id: 3}) Absolute URL: https://example.com/products/3
asset('css/app.css') Public path of a static file, aware of base paths and CDNs
absolute_url('/x') Turns a path into an absolute URL
csrf_token('delete-item') Generates a CSRF token for a form or link
is_granted('ROLE_ADMIN') Checks a permission (see authorization)
render(controller('App\\Controller\\X::y')) Embeds the output of another controller
TWIG
{# real Twig, read-only #}
<a href="{{ path('product_show', {id: product.id}) }}">{{ product.name }}</a>
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<meta property="og:url" content="{{ url('product_show', {id: product.id}) }}">

Always build links with path() instead of typing URLs, so that renaming a route's URL pattern never breaks a template. See generating URLs. The global variable app gives you the current request, session and user: app.request.locale, app.user, app.flashes.

Tests

A test checks a condition and is used with is (or is not) inside if or any boolean context. The built-in ones:

Test True when
defined the variable exists
empty the value is empty ('', [], 0, null, false)
null the value is null
even / odd an integer is even or odd
iterable the value can be looped over
divisible by(n) divisible by n
same as(x) identical (===) to x
TWIG
{# real Twig, read-only #}
{% if comments is empty %}No comments yet.{% endif %}
{% if user.nickname is defined and user.nickname is not null %}...{% endif %}
{% if loop.index is divisible by(3) %}<hr>{% endif %}

The value of is not is that it reads like English: {% if items is not empty %} instead of the harder {% if not (items is empty) %}.

flowchart LR
    V["Value<br/>products"] -->|"filter(p => p.stock > 0)"| F["In-stock list"]
    F -->|"map(p => p.name)"| M["Names"]
    M -->|"join(', ')"| J["'Lamp, Pen'"]
    J -->|"escape (automatic)"| O["Safe HTML output"]

Filters chain left to right, and the final printed value is escaped unless it is marked safe.

A filter pipeline you can run

The stand-in below evaluates {{ ... }} expressions with a registry of filters and functions, supports ~ for concatenation, hash and list literals, and HTML-escapes the result unless the last filter was raw. It is not Twig's parser (which builds a full expression tree), but the registry idea is exactly how Twig works: a filter is just a named callable.

PHP Filters, functions and escaping (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each line of output is one filter or function at work. The two lines printing html show the key rule: without raw the value is escaped, with raw it is passed through untouched.

Escaping in depth

Twig escapes every {{ }} output for the context given by the template's file name (HTML for .html.twig). The rules to remember:

  • Escaping happens at output time, after all filters. A filter chain's result is escaped once.
  • |raw marks a value as already safe. It is a statement of trust: the output goes to the browser exactly as it is.
  • Values that Twig functions return as safe markup are not escaped again, for example the HTML produced by form_widget() or include().
  • |striptags removes tags but is not a sanitizer for untrusted HTML. Use a proper sanitizer such as Symfony's HtmlSanitizer component before using |raw.
  • For attributes and scripts use the matching strategy: {{ value|e('html_attr') }}, {{ value|e('js') }}, {{ value|e('url') }}. The default HTML strategy is not safe inside a <script> block.
  • Passing data to JavaScript: put it in a data-* attribute with normal escaping, and read it with dataset, instead of printing it inside a script block.

Every |raw is a potential cross-site scripting hole. Before you add one, ask where the value came from. If a user could have influenced it, sanitize it first.

Loops and the loop variable

You met for already; here is the complete toolbox. Inside a loop Twig defines loop.index (from 1), loop.index0, loop.revindex, loop.revindex0, loop.first, loop.last and loop.length. You can loop with keys, over ranges, and with a combined if through the filter filter:

TWIG
{# real Twig, read-only #}
{% for key, label in {'a': 'Alpha', 'b': 'Beta'} %}
    {{ key }} = {{ label }}
{% endfor %}

{% for i in 1..3 %}{{ i }}{% if not loop.last %}, {% endif %}{% endfor %}

{% for product in products|filter(p => p.stock > 0) %}
    <li class="{{ cycle(['odd', 'even'], loop.index0) }}">{{ product.name }}</li>
{% endfor %}

Twig has no break or continue statements. That keeps templates declarative: select what you need with filter, slice or batch, then loop over the result.

Tests and conditions you can run

The second stand-in adds tests (is even, is empty, is divisible by(3)), an if/else and a for with the loop variable. Notice how a test reads like English, and how the loop context is rebuilt for every iteration.

PHP Tests, if/else and loop (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both n is even and n is divisible by(3) are registered tests, just as a custom Twig test would be (the next lesson shows how to add your own).

Choosing the right tool

  • Reshaping a value for display: a filter.
  • Producing a value from nothing or from framework state (a URL, an asset path, a token): a function.
  • Answering a yes/no question inside a condition: a test.
  • Anything needing a database query, a service call or business rules: do it in the controller or a custom extension, then pass the result to the template.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line correctly builds a link to a route named product_show?

    path() builds a relative URL from the route name and parameters, so URL patterns can change without touching templates.
  2. 2. What is the difference between a Twig filter and a Twig test?

    Filters use the pipe and return a transformed value. Tests use is or is not and return a boolean.
  3. 3. A comment contains <script>. What does {{ comment|raw }} do?

    raw disables escaping. Use it only for HTML you trust or have sanitized.
  4. 4. What does {{ items|default('none') }} do?

    default supplies a fallback for empty or undefined values.
  5. 5. Which variable tells you that you are on the last iteration of a for loop?

    loop.last is true on the final iteration; loop.length is the total number of items.

Summary

  • Filters (|) transform values, functions (name()) produce them, and tests (is) answer yes or no.
  • Useful filters: default, join, length, slice, date, number_format, map, filter; useful functions: range, max, min, cycle.
  • Symfony adds path(), url(), asset(), csrf_token() and is_granted(); always build links with path().
  • Output is escaped for HTML by default; |raw is a trust decision, and |striptags is not a sanitizer.
  • for offers the loop variable, key/value iteration, ranges and else; select data with filters before looping.

Next up: Custom Twig Extensions.