在树枝中使用 merge() 时,键值被“键"替换 [英] key value being replaced by 'key' when using merge() in twig

查看:20
本文介绍了在树枝中使用 merge() 时,键值被“键"替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将键值对添加到数组中,并为所有不以_"开头的属性添加当前值.出于某种原因,合并将key"(即 slug)的值替换为字符串 'key'.

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

例如,当 slug 是唯一一个键不以'_'开头的属性时,

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

key = slug
value = something

它的行为如下:

{% 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.

最终转储返回

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

在我期待的时候

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

我会说这是一个与 Twig forgets array-keys 类似的问题,但结论关于那个问题,这是一个 mongodb 问题,我没有使用它.我正在处理请求中的属性.

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.

由于某种原因,merge({ key : value}) 的行为类似于 merge({ 'key' : value}).

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

推荐答案

您需要将变量用括号括起来才能将其用作键.

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

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

这篇关于在树枝中使用 merge() 时,键值被“键"替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆