Twig: Is there a way to destructuring an array ?

Created on 11 Mar 2020  Â·  5Comments  Â·  Source: twigphp/Twig

Something like :

{{ '%s %s %s'|format(...params) }}

Most helpful comment

That would be awesome! Or being able to do something like :

{% set [variable1, variable2] = some_twig_function_returning_an_array() %}
{{ dump(variable1, variable2) }}

All 5 comments

No, there is no such operator in Twig.

That would be awesome! Or being able to do something like :

{% set [variable1, variable2] = some_twig_function_returning_an_array() %}
{{ dump(variable1, variable2) }}

I made a format_from_array twig filter as a workaround :

{{ '%s %s %s'|format_from_array(params) }}
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class FormatFromArrayExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [new TwigFilter('format_from_array', [$this, 'formatFromArray'])];
    }

    public function formatFromArray(string $format, array $params = []): string
    {
        return sprintf($format, ...$params);
    }
}

@maidmaid this is argument unpacking (using spread operator ...), not destructuring. How qul would that be though:

{% set items = [{code: 1, name: 'foo'}, {code: 2, name: 'bar}] %}

{% for [code, name] in items %}
     {{ code }}: {{name}}
{% endfor %}

@mikemix In your example the syntax should be {% for {code, name} in items %} if anything. [x, y] is for unpacking tuples.

Was this page helpful?
0 / 5 - 0 ratings