Twig
Twig copied to clipboard
Is there a way to destructuring an array ?
Something like :
{{ '%s %s %s'|format(...params) }}
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.