Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

key value being replaced by 'key' when using merge() in twig

I am trying to add pairs of key value to an array with their current values for all those attributes not starting by '_'. For some reason, the merge replaces the value of "key" (i.e slug) with the string 'key'.

For example when slug is the only attribute with key not starting with '_',

key = slug
value = something

it behaves as follows:

{% for key,value in app.request.attributes.all %}
    {% if '_' != key | slice(0, 1) %}
        {{ dump(key) }}  // string(4) "slug"
        {% set params = params | merge({ key : value}) %}
        {{ dump(key) }} // string(4) "slug"
    {% endif %}
{% endfor %}
{{ dump(params) }} // array(1) { ["key"]=> string(9) "something" }

I have added what the dumps return next to them.

The final dump returns

array(1) { ["key"]=> string(9) "something" }

while i'm expecting

array(1) { ["slug"]=> string(9) "something" }

I'd say it's a similar problem to Twig forgets array-keys but the conclusion on that question is that is a mongodb problem and I am not using it. I am working with attributes from the request.

For some reason, the merge({ key : value}) is behaving as merge({ 'key' : value}).

like image 984
mezod Avatar asked Mar 16 '13 20:03

mezod


2 Answers

With numeric keys you can lose your key in the process, with the m̀erge`filter.

I couldn't find any documentation about the '+' operator applied with arrays, but it works well in this case:

{% set array = {(1): 2} + array %}

Source: https://github.com/twigphp/Twig/issues/2741#issuecomment-417445042

like image 82
Laurent W. Avatar answered Nov 07 '22 10:11

Laurent W.


You need to wrap your variable with parenthesis to be able to use it as a key.

{% set params = params | merge({ (key) : value}) %}
like image 31
Thomas Potaire Avatar answered Nov 07 '22 09:11

Thomas Potaire