From 71bdb1af1a66de8b7a5400beb6b792a9e5bf1fe1 Mon Sep 17 00:00:00 2001 From: Antoine Veldhoven Date: Sun, 18 Oct 2026 21:44:02 +0200 Subject: [PATCH] Allow for-loop for stdClass-objects. --- src/Extension/CoreExtension.php | 8 ++++++ tests/Fixtures/tags/for/stdClass.test | 35 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 tests/Fixtures/tags/for/stdClass.test diff --git a/src/Extension/CoreExtension.php b/src/Extension/CoreExtension.php index 410597bbb1e..60f2a06c8eb 100644 --- a/src/Extension/CoreExtension.php +++ b/src/Extension/CoreExtension.php @@ -951,6 +951,10 @@ public static function keys($array): array return $keys; } + if ($array instanceof \stdClass) { + $array = (array) $array; + } + if (!\is_array($array)) { return []; } @@ -1396,6 +1400,10 @@ public static function ensureTraversable($seq) return $seq; } + if ($seq instanceof \stdClass) { + return (array) $seq; + } + return []; } diff --git a/tests/Fixtures/tags/for/stdClass.test b/tests/Fixtures/tags/for/stdClass.test new file mode 100644 index 00000000000..22e0973700b --- /dev/null +++ b/tests/Fixtures/tags/for/stdClass.test @@ -0,0 +1,35 @@ +--TEST-- +"for" tag iterates over stdClass objects +--TEMPLATE-- +{% for item in stdClass.obj %} + * {{ item }} + * {{ loop.index }}/{{ loop.index0 }} + * {{ loop.first }} + +{% endfor %} + +{% for key, value in stdClass.obj %} + * {{ key }}/{{ value }} +{% endfor %} + +{% for key in stdClass.obj|keys %} + * {{ key }} +{% endfor %} +--DATA-- +return ['stdClass' => (object) ['obj' => (object) ['key1' => 'one', 'key2' => 'two']]] +--EXPECT-- + * one + * 1/0 + * 1 + + * two + * 2/1 + * + + + * key1/one + * key2/two + + * key1 + * key2 +