Setting element of array from Twig

前端 未结 10 741
北恋
北恋 2020-12-04 09:55

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

I tried doing it next way:

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

but

相关标签:
10条回答
  • 2020-12-04 10:20

    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') %}

    0 讨论(0)
  • 2020-12-04 10:23

    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'}) %}
    
    0 讨论(0)
  • 2020-12-04 10:24

    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_ ....

    0 讨论(0)
  • 2020-12-04 10:30

    You can also use the following syntax:

    {% set myArray = myArray + myArray2 %}
    
    0 讨论(0)
  • 2020-12-04 10:39
    {% 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.

    0 讨论(0)
  • 2020-12-04 10:40

    I had a multi dimension array. The only solution I could find out is create a new temporary array and update/add the information, which was further passed on to another twig function.

    0 讨论(0)
提交回复
热议问题