diff --git a/CHANGELOG b/CHANGELOG index 9411161d3..29cb43fca 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,7 @@ * fixed the spaceless filter so that it behaves like the spaceless tag * fixed BC break on Environment::resolveTemplate() * fixed the bundled Autoloader to also load namespaced classes + * allowed Traversable objects to be used in the "with" tag * 1.38.2 (2019-03-12) diff --git a/src/Node/WithNode.php b/src/Node/WithNode.php index 77364ac51..665aa4b12 100644 --- a/src/Node/WithNode.php +++ b/src/Node/WithNode.php @@ -40,6 +40,11 @@ class WithNode extends Node ->write(sprintf('$%s = ', $varsName)) ->subcompile($this->getNode('variables')) ->raw(";\n") + ->write(sprintf("if (\$%s instanceof \\Traversable) {\n", $varsName)) + ->indent() + ->write(sprintf("\$%s = iterator_to_array(\$%s);\n", $varsName, $varsName)) + ->outdent() + ->write("}\n") ->write(sprintf("if (!is_array(\$%s)) {\n", $varsName)) ->indent() ->write("throw new RuntimeError('Variables passed to the \"with\" tag must be a hash.');\n") diff --git a/test/Twig/Tests/Fixtures/tags/with/iterable.test b/test/Twig/Tests/Fixtures/tags/with/iterable.test new file mode 100644 index 000000000..1b0cbc63e --- /dev/null +++ b/test/Twig/Tests/Fixtures/tags/with/iterable.test @@ -0,0 +1,10 @@ +--TEST-- +"with" tag with an iterable expression +--TEMPLATE-- +{% with vars %} + {{ foo }}{{ bar }} +{% endwith %} +--DATA-- +return ['vars' => new ArrayObject(['foo' => 'baz', 'bar' => 'qux'])] +--EXPECT-- +bazqux