在twig中使用变量作为散列键(作为path()或| trans中的参数)

jac*_*ter 21 symfony twig

是否可以动态使用跨过滤器或路径功能?将变量作为参数?EX1:

{{ path('object_edit', { parameter_type : parameter_value }) }}
Run Code Online (Sandbox Code Playgroud)

因为:我不知道"对象"是否使用id或slug进行路由

EX2:

{{message|trans({ parameter_type : parameter_value }, 'TranslationDomain') }}
Run Code Online (Sandbox Code Playgroud)

因为:我不知道它是'%user%'还是'%article%'或其他什么

为什么这样可行:

{{ path('object_edit', { 'id' : parameter_value }) }}
Run Code Online (Sandbox Code Playgroud)

但这不是:

{{ set parameter_type = 'id' }}
{{ path('object_edit', { parameter_type : parameter_value }) }}
Run Code Online (Sandbox Code Playgroud)

s10*_*10z 54

{% set key = 'foobar' %}
{% set hash = { (key) : 'hello world' } %}
{% debug hash %}
Run Code Online (Sandbox Code Playgroud)

打印:

array(1) { ["foobar"]=> string(11) "hello world" } 
Run Code Online (Sandbox Code Playgroud)

用括号括起来解决你的问题.


小智 14

用括号(而不是大括号)括起哈希键.

{{ path('object_edit', { (parameter_type) : parameter_value }) }}
Run Code Online (Sandbox Code Playgroud)