Twig Constraint
7.3
The Twig constraint was introduced in Symfony 7.3.
Validates that a given string contains valid Twig syntax. This is particularly useful when template content is user-generated or configurable, and you want to ensure it can be rendered by the Twig engine.
Note
Using this constraint requires having the symfony/twig-bridge package
installed in your application (e.g. by running composer require symfony/twig-bridge).
| Applies to | property or method |
| Class | Twig |
| Validator | TwigValidator |
Basic Usage
Apply the Twig constraint to validate the contents of any property or the
returned value of any method:
1 2 3 4 5 6 7
use Symfony\Bridge\Twig\Validator\Constraints\Twig;
class Template
{
#[Twig]
private string $templateCode;
}
1 2 3 4 5 6 7 8 9 10
// src/Entity/Page.php
namespace App\Entity;
use Symfony\Bridge\Twig\Validator\Constraints\Twig;
class Page
{
#[Twig]
private string $templateCode;
}
Constraint Options
message
type: message default: This value is not a valid Twig template.
This is the message displayed when the given string does not contain valid Twig syntax:
1 2 3 4 5 6 7
// ...
class Page
{
#[Twig(message: 'Check this Twig code; it contains errors.')]
private string $templateCode;
}
This message has no parameters.
skipDeprecations
type: boolean default: true
If true, Twig deprecation warnings are ignored during validation. Set it to
false to trigger validation errors when the given Twig code contains any deprecations:
1 2 3 4 5 6 7
// ...
class Page
{
#[Twig(skipDeprecations: false)]
private string $templateCode;
}
This can be helpful when enforcing stricter template rules or preparing for major Twig version upgrades.