This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Expose the escaping strategy a template was compiled with
Compiled templates now record the escaping strategy they were compiled with and expose it via `TemplateWrapper::getDefaultEscapeStrategy()`, so the strategy of a template can be known without deriving it again from its name, which is both slower and can disagree with how its content was actually escaped.
Commits
-------
26812ebc0d Expose the escaping strategy a template was compiled with
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Improve macro call performance
This is mostly about getting back to the same performance we had in 3.28.
Commits
-------
a8ee6dd762 Improve macro call performance
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Fix IntlExtension inheriting values derived by ICU from a date formatter prototype
Commits
-------
6671288259 Fix IntlExtension inheriting values derived by ICU from a date formatter prototype
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Fix array access with a Stringable key on subclasses of ArrayObject and ArrayIterator
Commits
-------
4aae99e92c Fix array access with a Stringable key on subclasses of ArrayObject and ArrayIterator
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Report a clear error when a string cannot be split into characters
Commits
-------
1ee9dae55a Cover and document the matches operator throwing on an invalid UTF-8 subject
5c1be030c5 Report a clear error when a string cannot be split into characters
This PR was merged into the 3.x branch.
Discussion
----------
Deprecate cloning a Twig environment
Commits
-------
55afb2e084 Deprecate cloning a Twig environment
This PR was merged into the 3.x branch.
Discussion
----------
Report the macro call parentheses deprecation once per call site and name the macro
Commits
-------
40d57c6445 Report the macro call parentheses deprecation once per call site and name the macro
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Reject template wrappers from another environment
Twig now rejects `TemplateWrapper` instances created by another `Environment`.
This prevents templates from unexpectedly using another environment's loader, extensions, globals, or sandbox policy.
Commits
-------
83e8f7e123 Reject cross-environment template wrappers in block chains
c1fc112047 Reject cross-environment template wrappers
This PR was merged into the 3.x branch.
Discussion
----------
Report a clear error when using macros imported in a template body that was not rendered
Commits
-------
72c2f669bd Report a clear error when using macros imported in a template body that was not rendered
This PR was merged into the 3.x branch.
Discussion
----------
Allow block chains to be composed of other block chains
This is something that is needed by Symfony (and other OSS projects), so better to have it directly in Twig.
Commits
-------
d6b81f9074 Allow block chains to be composed of other block chains
This PR was merged into the 3.x branch.
Discussion
----------
Resolve block chains against the render context
While working on the Symfony PR for #4917, I realize that the performance was worse with the Twig's way. #4924 fixes part of the performance "regression". This one closes the gap.
`BlockChain` currently freezes each template's lineage by cloning it, so the block map and `parent()` both resolve `{% extends %}` against the constructor context.
This PR changes that to resolve the chain against the render context instead. `hasBlock()` and `getBlockNames()` take a context, like `TemplateWrapper` already does, and the third constructor argument becomes a default the render context can override. A lineage whose templates all have a fixed parent (none, or constant) is resolved once and cached, so the common case costs nothing; a dynamic `{% extends %}` re-resolves per call (not use by Symfony anyway).
This fixes also an inconsistency: a chained template with a dynamic parent now behaves exactly as it does when rendered directly. It also removes all changes in the "core" logic of Template.
```
construct render 1 chain + 40 renders
Symfony's engine today 13.44us 0.78us 50.3us
#4917 ~70us 0.96us ~117us
this PR 0.61us 0.84us 53.0us
```
Commits
-------
897717d78f Resolve block chains against the render context instead of freezing lineages
This PR was merged into the 3.x branch.
Discussion
----------
Resolve constant parent templates once instead of on every lookup
Currently, `Template::$parent` is only memoized by the compiled `doDisplay()`. Anything that reaches a template through `getParent()` without rendering it (`TemplateWrapper::hasBlock()`, `getBlockNames()`, `renderBlock()`, `yieldParentBlock()`, `MacroNamespace::getParent()`) re-evaluates `doGetParent()` and re-runs the sandbox check on every call, even when the parent is a string literal.
`doGetParent()` now does `$this->parent ??= $this->load("name", $line)` for a constant parent, which is what `doDisplay()` already does one line later. Dynamic parents are untouched and still resolve per context.
This also fixes a bug: `getParent()` loaded a constant parent with line `-1`, so a missing parent reported through `hasBlock()`/`getBlockNames()` lost its line number, while `render()` reported the `{% extends %}` line. All three now agree.
Commits
-------
c53b6468c9 Resolve constant parent templates once instead of on every lookup
This PR was merged into the 3.x branch.
Discussion
----------
Fix wrapping the Twig cache pool in a second tag aware adapter
`twig/extra-bundle` wires the `{% cache %}` pool like this:
```php
->set('twig.cache', TagAwareAdapter::class)
->args([$service('.twig.cache.inner')])
->set('.twig.cache.inner')
->parent('cache.app')
->tag('cache.pool', ['name' => 'twig.cache'])
```
`.twig.cache.inner` is a child of `cache.app`, so when an application configures
`framework.cache.app` with a natively tag aware adapter (`cache.adapter.redis_tag_aware`,
or the valkey, pdo and mongodb variants), the child pool is *already* a
`TagAwareAdapterInterface` and `twig.cache` wraps it in a second `TagAwareAdapter`.
Two nested `TagAwareAdapter`s never read back what they wrote:
```php
$pool = new TagAwareAdapter(new TagAwareAdapter(new ArrayAdapter()));
$item = $pool->getItem('k');
$item->set('value')->tag('t1');
$pool->save($item);
var_dump($pool->getItem('k')->isHit()); // bool(false)
```
So every `{% cache %}` block silently misses, on every request. This was reported here as
twigphp/Twig#3636 (the workaround in that thread is to redefine `twig.cache` and
`.twig.cache.inner` by hand as a `RedisTagAwareAdapter`), and again on the Symfony side as
symfony/symfony#54339 by `@rpkamp`. Symfony first tried to fix it in symfony/symfony#57927 by
deprecating passing a tag aware pool to `TagAwareAdapter`, but `@keulinho`'s analysis in
symfony/symfony#58830 showed that the deprecated thing was not the culprit, so that
deprecation was reverted in symfony/symfony#58950 and the defect was left where it is: in
this bundle. Symfony's own cache wiring already gets this right, it aliases
`cache.app.taggable` to `cache.app` when the configured adapter is natively tag aware
instead of decorating it.
## The fix
A small compiler pass resolves the parent chain of `.twig.cache.inner` and, when the
adapter it ends up on implements `TagAwareAdapterInterface`, drops the decorator and
aliases `twig.cache` to the pool. Nothing changes for the common case of a plain
`cache.app`, where the decorator is what makes the pool taggable and stays in place.
I picked this over declaring the pool through `framework.cache.pools` (with `tags: true`,
which would let Symfony make the same decision) because the pool is only registered when
the `cache` extension is enabled, and reproducing that condition inside a `prepend()` call
means processing the bundle's own configuration before `load()` runs. The compiler pass
stays entirely inside the bundle and only acts when `twig.cache` exists.
Detecting tag awareness from the resolved adapter class rather than from a list of adapter
ids keeps this working across `^5.4|^6.4|^7.0|^8.0` even though the set of natively tag
aware adapters grew over that range, and it also covers a `cache.app` overridden with a
custom tag aware adapter.
Two constraints are covered by the tests: `twig.cache` keeps its own namespace instead of
collapsing into the application pool, and the three argument aliases
(`TagAwareCacheInterface $twigCache`, `CacheInterface $twigCache`,
`CacheItemPoolInterface $twigCache`) keep resolving.
## Verification
Compiled containers with `framework.cache.app` left at its default and set to
`cache.adapter.redis_tag_aware`, before and after the patch:
| `framework.cache.app` | before | after |
| --- | --- | --- |
| default (filesystem) | `TagAwareAdapter(FilesystemAdapter)` | unchanged |
| `cache.adapter.redis_tag_aware` | `TagAwareAdapter(RedisTagAwareAdapter)` | `RedisTagAwareAdapter` |
| `cache.adapter.valkey_tag_aware` | `TagAwareAdapter(RedisTagAwareAdapter)` | `RedisTagAwareAdapter` |
| `cache.adapter.redis` | `TagAwareAdapter(RedisAdapter)` | unchanged |
In the fixed tag aware case the pool namespace stays distinct from `cache.app`'s.
`extra/twig-extra-bundle` test suite, on Symfony 8.2-dev and on framework-bundle 6.4:
```
PHPUnit 9.6.36 by Sebastian Bergmann and contributors.
Testing
................... 19 / 19 (100%)
Time: 00:00.534, Memory: 28.00 MB
OK (19 tests, 100 assertions)
```
The two new tests fail without the pass:
```
1) TwigCachePoolPassTest::testThePoolIsNotDecoratedWhenTheAppAdapterIsTagAware
Failed asserting that two strings are identical.
-'@.twig.cache.inner'
+'Symfony\Component\Cache\Adapter\TagAwareAdapter'
```
Commits
-------
bd939c8c3a Fix wrapping the Twig cache pool in a second tag aware adapter
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Template runtime and block composition
This PR addresses the Symfony compatibility break from #4910
It introduces runtime composition of templates used as collections of named block renderers: The renderer provides an ordered set of unrelated templates. The first matching block wins, nested `block()` calls see the complete composed set, and `parent()` remains within the block’s own inheritance or `use` hierarchy.
This feature is going to be useful for more than just Symfony.
## Strong non-Symfony use cases
### Ibexa Core
**Project:** `ibexa/core`
**Feature:** CMS field rendering through `FieldBlockRenderer`
Ibexa maintains prioritized field templates, selects blocks such as `ibexa_string_field`, walks parent templates, constructs a block map and passes it to `renderBlock()`.
This is the strongest independent fit for `BlockChain`:
```php
$blocks = new BlockChain($twig, [
$localTemplate,
...$projectFieldThemes,
...$vendorFieldThemes,
]);
return $blocks->renderBlock($fieldType.'_field', $context);
```
### Data-grid and listing renderers
The audit found the same broad mechanism in:
- `Prezent/prezent-grid`, `src/Twig/GridRenderer.php`
- `pawellen/listing`, `Renderer/ListingRenderer.php`
- `Braunstetter/data-grid-bundle`, `src/GridRendererEngine.php`
- `AnoDataGrid`, `DataGridExtension.php`
Their common feature is **layered grid themes**:
1. Configure default grid templates.
2. Add per-grid or per-view overrides.
3. Map a column type to a block name.
4. Walk template inheritance.
5. Merge or cache available blocks.
6. Render the selected cell, header or filter block.
Several accessed `unwrap()`, `getBlocks()` or `getParent()` directly; others passed manually assembled block maps into `renderBlock()` or `displayBlock()`.
## Adjacent use cases
The audit also found block-library patterns that could benefit if they grow into multi-template composition:
- **iTop:** plugin-contributed login blocks such as `login_input`, `login_submit`, `login_form_footer` and `login_links`; independently renders `body`, `script`, `ready_script` and `css`.
- **Email renderers:** independently render `subject`, `body_text` and `body_html` blocks.
- **Runtime theme overlays:** tenant branding, application skins, email themes, reports and configurable admin interfaces.
- **Extension-provided block libraries:** enabled modules contribute blocks such as `toolbar`, `field_text`, `dashboard_metric` or `login_footer`.
- **Testing and preview tooling:** render a block against an exact theme stack without generating a synthetic host template.
## Important negative finding
Shopware-style plugin inheritance, and similar Drupal or Sylius layering, are **not** considered a direct fit. Those systems expect `parent()` to call the next plugin override. `BlockChain` deliberately keeps `parent()` inside the defining template’s normal lineage.
Commits
-------
49f814ea26 Template runtime and block composition
The ".twig.cache.inner" pool is a child of "cache.app". When the application
configures a natively tag aware adapter for it (redis, valkey, pdo or mongodb),
the child pool is already tag aware and decorating it with a TagAwareAdapter
turns every read into a miss.
Alias "twig.cache" to the pool in that case, the way Symfony aliases
"cache.app.taggable" to "cache.app" instead of decorating it. The pool keeps
its own namespace, so it does not start sharing the application pool's one, and
the decorator stays in place for the plain adapters that need it.
This PR was merged into the 3.x branch.
Discussion
----------
Check that the use tag is allowed before resolving trait templates
Commits
-------
18863f0371 Check that the use tag is allowed before resolving trait templates
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Fix `TemplateWrapper::hasBlock()` and `TemplateWrapper::getBlockNames()` omitting environment globals
Commits
-------
0e1852632f Fix `TemplateWrapper::hasBlock()` and `TemplateWrapper::getBlockNames()` omitting environment globals
This PR was merged into the 3.x branch.
Discussion
----------
Fix html_attr dropping style declarations whose value is zero
`InlineStyle::getValue()` skips a declaration when `empty($value)` is true. That also matches `0`, `0.0` and `'0'`, which are ordinary CSS values.
```twig
{{ html_attr({style: {opacity: 0}}) }} {# "" #}
{{ html_attr({style: {'flex-grow': 0, color: 'red'}}) }} {# style="color: red;" #}
{{ html_attr({style: ['opacity: 0']}) }} {# style="opacity: 0;" #}
{{ html_attr({class: [0, 'a']}) }} {# class="0 a" #}
```
Same declaration, opposite result. The numeric-key branch never consults `empty()`, and the sibling `SeparatedTokenList::getValue()` already uses an explicit `null !== $v && false !== $v` test, so token lists keep a `0`. When every declaration is dropped the attribute is omitted entirely, so `{style: {opacity: 0}}` renders nothing at all, and `HtmlExtension::htmlAttrValue('style', ['opacity' => 0])` returns `null`.
Silently affects `opacity`, `z-index`, `margin`, `padding`, `border`, `flex-grow` and custom properties.
The guard now lists the values that carry no declaration. `null`, `false`, `''` and `true` still skip, and `[]` is kept in that list so empty arrays behave exactly as before.
`html_attr.rst` documents the `null`/`false`/`true` omission rules and says nothing about zero, so no doc change is needed. `HtmlAttrTest.php` already has a case named "zero is not treated as falsy", but only for a plain attribute value.
3 tests added. Reverting the fix fails the first; a naive `null`/`false`-only guard fails the other two.
Commits
-------
c072ff85b3 Fix html_attr dropping style declarations whose value is zero
InlineStyle::getValue() skipped a declaration when empty($value) was true,
which also matches 0, 0.0 and '0'. Those are ordinary CSS values (opacity: 0,
z-index: 0, margin: 0, flex-grow: 0), so they were silently dropped, and a
style map containing only such declarations omitted the attribute entirely.
The sibling SeparatedTokenList::getValue() already uses an explicit
null/false test, so class token lists keep a 0 while style declarations did
not. The numeric-key branch of InlineStyle itself never consulted empty(),
so {style: ['opacity: 0']} printed while {style: {opacity: 0}} did not.
This PR was merged into the 3.x branch.
Discussion
----------
Fix the default filter fallback reusing a null-safe temporary variable
The `default` filter reuses the fallback argument node in both branches of the conditional it compiles to. Because `GetAttrExpression` records the temporary variable it allocated for a null-safe chain on the node itself, the second compilation skipped the assignment and emitted a bare `$_vN` reference, so `{{ item?.label|default(item?.name) }}` warned about an undefined variable whenever `item` was null.
The fallback node is now cloned, like the node used for the defined test already is, so each branch compiles its own temporary.
Fixes#4914
Commits
-------
2d0c30b075 Remove redundant default filter cases
0b4199c522 Strengthen the default filter regression test
86c830ef45 Fix the default filter fallback reusing a null-safe temporary variable
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Remove the documentation comments compilation overhead
Documentation comments are now attached to semantic nodes during parsing, removing the dedicated AST traversal. Token parsers returning placeholder nodes can select the semantic documentation target.
Commits
-------
60eed4ccd5 Remove the documentation comments compilation overhead