Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Is there a way to destructuring an array ?

Open maidmaid opened this issue 5 years ago • 5 comments

Something like :

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

maidmaid avatar Mar 11 '20 14:03 maidmaid

No, there is no such operator in Twig.

stof avatar Mar 12 '20 08:03 stof

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

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

gnutix avatar Apr 21 '20 09:04 gnutix

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 avatar Apr 21 '20 12:04 maidmaid

@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 avatar May 13 '20 10:05 mikemix

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

mnpenner avatar Sep 19 '20 21:09 mnpenner