Twig

The flexible, fast, and secure
template engine for PHP

a Symfony Product
Docs Tags types
You are reading the documentation for Twig 3.x. Switch to the documentation for Twig 1.x, 2.x.

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

types

3.13

The types tag was added in Twig 3.13. This tag is experimental and can change based on usage and feedback.

Use the types tag to declare the type of a variable:

1
2
{% types is_correct: 'boolean' %}
{% types score: 'number' %}

Or multiple variables:

1
2
3
4
{% types
    is_correct: 'boolean',
    score: 'number',
%}

You can also enclose types with {}:

1
2
3
4
{% types {
    is_correct: 'boolean',
    score: 'number',
} %}

Declare optional variables by adding a ? suffix:

1
2
3
4
{% types {
    is_correct: 'boolean',
    score?: 'number',
} %}

By default, this tag does not affect the template compilation or runtime behavior.

Its purpose is to enable designers and developers to document and specify the context's available and/or required variables. While Twig itself does not validate variables or their types, this tag enables extensions to do this.

Additionally, Twig extensions can analyze these tags to perform compile-time and runtime analysis of templates.

Note

The types declared in a template are local to that template and must not be propagated to included templates. This is because a template can be included from multiple different places, each potentially having different variable types.

Note

The syntax for and contents of type strings are intentionally left out of scope.