Setting element of array from Twig

2019-01-12 22:17发布

How can I set member of an already existing array from Twig?

I tried doing it next way:

{% set arr['element'] = 'value' %}

but I got the following error:

Unexpected token "punctuation" of value "[" ("end of statement block" expected) in ...

标签: php twig
8条回答
Evening l夕情丶
2楼-- · 2019-01-12 22:28
{% set links = {} %}

{# Use our array to wrap up our links. #}
{% for item in items %}
  {% set links = links|merge({ (loop.index0) : {'url': item.content['#url'].getUri(), 'text': item.content['#title']} }) %}
{% endfor %}

{%
set linkList = {
  'title': label,
  'links': links
}
%}

{% include '<to twig file>/link-list.twig'%}

Thanks for this thread -- I was also able to create an array with (loop.index0) and send to twig.

查看更多
Bombasti
3楼-- · 2019-01-12 22:31

There is no nice way to do this in Twig. It is, however, possible by using the merge filter:

{% set arr = arr|merge({'element': 'value'}) %}
查看更多
混吃等死
4楼-- · 2019-01-12 22:33

I've found this issue very annoying, and my solution is perhaps orthodox and not inline with the Twig philosophy, but I developed the following:

$function = new Twig_Function('set_element', function ($data, $key, $value) {
    // Assign value to $data[$key]
    if (!is_array($data)) {
        return $data;
    }
    $data[$key] = $value;
    return $data;
});
$twig->addFunction($function);

that can be used as follows:

{% set arr = set_element(arr, 'element', 'value') %}

查看更多
等我变得足够好
5楼-- · 2019-01-12 22:38

I ran into this problem but was trying to create integer indexes instead of associative index like 'element'.

You need to protect your index key with () using the merge filter as well:

{% set arr = arr|merge({ (loop.index0): 'value'}) %} 

You can now add custom index key like ('element'~loop.index0)

查看更多
Anthone
6楼-- · 2019-01-12 22:38

I have tried @LivaX 's answer but it does not work , merging an array where keys are numeric wont work ( https://github.com/twigphp/Twig/issues/789 ).

That will work only when keys are strings

What I did is recreate another table ( temp) from the initial table (t) and make the keys a string , for example :

{% for key , value in t%}
{% set temp= temp|merge({(key~'_'):value}) %}
{% endfor %}

t keys : 0 , 1 , 2 ..

temp keys : 0_, 1_ , 2_ ....

查看更多
迷人小祖宗
7楼-- · 2019-01-12 22:47

If initialization only need:

{% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %}
查看更多
登录 后发表回答