key value being replaced by 'key' when usi

2019-04-23 07:49发布

问题:

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}).

回答1:

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

{% set params = params | merge({ (key) : value}) %}