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}).
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
You need to wrap your variable with parenthesis to be able to use it as a key.
{% set params = params | merge({ (key) : value}) %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With