From aa754cafacbd3e6df6350fc4def28e710fe64761 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 20 Oct 2026 10:47:54 +0200 Subject: [PATCH] Speed up the `with` tag by adding the globals to the new context in place --- CHANGELOG | 1 + src/Node/WithNode.php | 6 +++++- tests/Fixtures/tags/with/precedence.test | 15 +++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 tests/Fixtures/tags/with/precedence.test diff --git a/CHANGELOG b/CHANGELOG index 9d62152919a..29877160b34 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ # 3.31.0 (2026-XX-XX) + * Speed up the `with` tag by adding the globals to the new context in place * Fix `html_cva()` ignoring a boolean default variant * Fix a PHP 8.5 deprecation in `html_cva()` when a recipe value is `null` * Add the `collate` function to `twig/intl-extra` to compare strings in the alphabetical order of a locale diff --git a/src/Node/WithNode.php b/src/Node/WithNode.php index 487e2800bfd..6adf89eab3a 100644 --- a/src/Node/WithNode.php +++ b/src/Node/WithNode.php @@ -61,7 +61,11 @@ public function compile(Compiler $compiler): void $compiler->write("\$context = [];\n"); } - $compiler->write(\sprintf("\$context = \$%s + \$context + \$this->env->getGlobals();\n", $varsName)); + // two statements: adding the globals in place copies the context once instead of twice + $compiler + ->write(\sprintf("\$context = \$%s + \$context;\n", $varsName)) + ->write("\$context += \$this->env->getGlobals();\n") + ; } $compiler diff --git a/tests/Fixtures/tags/with/precedence.test b/tests/Fixtures/tags/with/precedence.test new file mode 100644 index 00000000000..64a5ac8a9f2 --- /dev/null +++ b/tests/Fixtures/tags/with/precedence.test @@ -0,0 +1,15 @@ +--TEST-- +"with" tag gives precedence to its variables, then to the context, then to the globals +--TEMPLATE-- +[{% with {global: 'with'} %}{{ global }}{% endwith %}] +{% set global = 'context' %} +[{% with {foo: 'with'} %}{{ global }}{% endwith %}] +[{% with {foo: 'with'} only %}{{ global }}{% endwith %}] +[{{ global }}] +--DATA-- +return [] +--EXPECT-- +[with] +[context] +[global] +[context]