Twig 3.31.0 is out. It adds a collate() function to sort strings in the
alphabetical order of a language, lets you mark a Markup value as safe for
some escaping strategies only, makes attribute-based extensions easier to
write and to load lazily, and makes the compiled template cache reproducible
across directories.
Sorting Strings in the Order of a Language
The sort filter compares strings byte per byte: uppercase letters come
before lowercase ones and accented letters end up after z. The new
collate() function of twig/intl-extra compares two strings in the
alphabetical order of a locale, and plugs into the arrow function of
sort:
1 2 3 4 5 6
{# athlétisme, Boxe, Échecs, équitation, judo, Yoga #}
{{ sports|sort((a, b) => collate(a, b))|join(', ') }}
{% for city in cities|sort((a, b) => collate(a.name, b.name)) %}
{{ city.name }}
{% endfor %}
It uses the current locale by default, and accepts an explicit one as the
order depends on the language. Swap the arguments to sort in descending
order, and chain comparisons with ?: to sort on several criteria:
1 2 3 4 5 6
{% set by_name = (a, b) => collate(a.lastname, b.lastname, 'fr')
?: collate(a.firstname, b.firstname, 'fr') %}
{% for user in users|sort(by_name) %}
{{ user.lastname }} {{ user.firstname }}
{% endfor %}
Markup Values Safe for Some Escaping Strategies Only
A Twig\Markup instance used to be safe for every escaping strategy: an
HTML fragment wrapped in Markup was printed as-is even when the js or
css strategy applied. The constructor now takes an optional third argument
listing the strategies the content is safe for; it is printed as-is when one of
these strategies applies and escaped for any other one:
1 2 3 4 5 6 7
use Twig\Markup;
// safe for the html strategy, escaped for any other one
$badge = new Markup($html, 'UTF-8', ['html']);
// safe for all strategies, the default
$badge = new Markup($html, 'UTF-8');
The default stays ['all'], so existing code behaves as before.
Classes registered with EscaperExtension::addSafeClass() now follow the
same rules at runtime as the compiler: a class safe for html_attr is also
safe for html_attr_relaxed and html, and a class safe for
html_attr_relaxed is also safe for html.
The escaping documentation also gained a caution about values marked safe for
html (captures, macro calls, include(), is_safe callables, or
Markup instances): automatic escaping prints them as-is, even inside a
quoted HTML attribute where they can close the attribute. Escape them
explicitly there:
1
<img alt="{{ link|escape('html') }}">
Attribute-Based Extensions, Eager or Lazy
An extension class can now declare its filters, functions, and tests with the
#[AsTwigFilter], #[AsTwigFunction], and #[AsTwigTest] attributes
by extending AttributeExtension, instead of implementing getFilters(),
getFunctions(), and getTests():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
use Twig\Attribute\AsTwigFunction;
use Twig\Extension\AttributeExtension;
class InvoiceExtension extends AttributeExtension
{
public function __construct(private CurrencyConverter $converter)
{
}
#[AsTwigFunction('invoice_total')]
public function total(Invoice $invoice, string $currency): string
{
return $this->converter->format($invoice->getTotal(), $currency);
}
}
Register it as usual, or lazily so that its dependencies are only created the first time a template calls one of its callables:
1 2 3 4 5 6 7 8 9 10
use Twig\RuntimeLoader\FactoryRuntimeLoader;
// as usual
$twig->addExtension(new InvoiceExtension($converter));
// or lazily
$twig->addExtension(new AttributeExtension(InvoiceExtension::class));
$twig->addRuntimeLoader(new FactoryRuntimeLoader([
InvoiceExtension::class => fn () => new InvoiceExtension($converter),
]));
In both cases, $twig->getExtension(InvoiceExtension::class) returns the
InvoiceExtension instance.
Starting with Symfony 8.2, there is nothing to configure: TwigBundle
registers the autoconfigured extensions that declare their callables only
with attributes, including subclasses of AttributeExtension, the lazy
way. Each one is then created the first time a template calls one of its
filters, functions, or tests. Symfony's own extensions, such as the routing
one, are registered the same way, which makes getting the twig service
noticeably cheaper.
Reproducible Template Caches
Compiled templates embedded the absolute path of their source, so warming the cache of the same application in two directories never produced identical files, and errors reported paths of the build directory. When debug is disabled, compiled templates now ask the loader for that path only when they need it, typically when reporting an error. Building the same application in two directories now gives the same compiled templates, which makes it possible to warm the cache on a build server.
Performance
As usual, this release also comes with a bunch of performance improvements.
Full Changelog
- #5042 Skip caching class lists longer than 2 KB in
html_cva()(@nicolas-grekas) - #5043 Don't cache Intl formatters built from long patterns, attributes, or symbols (@nicolas-grekas)
- #5044 Fully normalize template names in FilesystemLoader (@nicolas-grekas, @fabpot)
- #5039 Fix a variable not being escaped when it has the name of a macro import alias of another scope (@jack-worman)
- #4985 Normalize the template name in FilesystemLoader::getSourceContext() (@KalimeroMK)
- #4987 Fix compiled templates depending on the directory of their source when debug is disabled (@nicolas-grekas)
- #5009 Speed up the
withtag by adding the globals to the new context in place (@nicolas-grekas) - #4995 Allow extending AttributeExtension to declare callables with attributes (@GromNaN)
- #5017 Fix html_cva() ignoring a boolean default variant (@fabpot)
- #5014 Fix PHP 8.5 deprecation in html_cva() when a recipe value is null (@goba)
- #4997 Add the collate function to compare strings in the alphabetical order of a locale (@fabpot)
- #4989 Allow registering an extension class lazily with
AttributeExtension(@nicolas-grekas) - #4991 Allow marking a Markup instance as safe for some escaping strategies only (@fabpot)
- #4990 Consider a class safe for html_attr also safe for html_attr_relaxed and html at runtime (@fabpot)
- #4992 Fix reading an attribute through its getter initializing a lazy object when the property is not public (@abp002)
- #4984 Speed up applying
html_cva()recipes that resolve to classes already seen (@Kocal) - #4988 Fix compiled float literals depending on the serialize_precision ini setting (@nicolas-grekas)
- #4954 Speed up loading compiled templates that OPcache already holds (@nicolas-grekas)
- #4976 Speed up traversing nodes with node visitors (@nicolas-grekas)
- #4951 Allow skipping the directory check when adding paths to
FilesystemLoader(@nicolas-grekas) - #4980 Fix the deprecated tag generating invalid PHP for an integer message (@fabpot)
- #4974 Fix the loop variable of a for tag being undefined in the sequence of a nested loop (@fabpot)
- #4979 Reject the spread operator outside sequences, mappings, and call arguments (@fabpot)
- #4964 Discard what the non-selected branch of a guard tag registers on the parser (@fabpot)
- #4960 Reset the escaping state when compiling a new template after a compilation error (@fabpot)
- #4959 Reject a Template instance created by another environment when resolving templates (@fabpot)
- #4972 Fix the sandbox not reporting the line of a rejected guard tag (@fabpot)
- #4965 Rewrite the sandbox documentation around what developers need to know (@fabpot)
- #4949 Skip the property checker call and memoize the class constant probe when reading an object attribute (@fabpot)
- #4947 Stop looking up a macro twice in its own namespace when it is declared by a parent (@fabpot)