方法的 Twig 变量变量
Twig Variable Variables for a method
我正在尝试做一些在 PHP 中非常容易但在 twig 中不那么容易的事情。
基本上,我需要调用一个 class 方法,但我需要能够定义要通过字符串调用的方法。
我有 3 种方法:getControlvs
、getControlnc
和 getControltr
。但是,为了调用这些方法,我需要一个单独的变量来确定要调用的方法。
这就是我现在尝试调用的内容:
{% set neutPer = key.getControl~neutFaction %}
其中 neutFaction
可以是 "vs"、"nc" 或 "tr"。
这似乎只触发了 key.getControl 然后就是这样,连接丢失了。
有什么想法吗?
提前致谢!
尝试{% set neutPer = (key.getControl~neutFaction) %}
或者您可以在将变量传递给 twig 的 controller/service 中更改此设置,这样您就不需要设置串联。
您可以使用 attribute twig function:
首先将字符串连接为:
{% set method = "getControl" ~ neutFaction %}
然后调用为
{{ attribute(key, method) }}
您也可以将参数传递为:
{{ attribute(key, method, arguments) }}
此外,定义的测试可以检查是否存在动态属性:
{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}
我正在尝试做一些在 PHP 中非常容易但在 twig 中不那么容易的事情。
基本上,我需要调用一个 class 方法,但我需要能够定义要通过字符串调用的方法。
我有 3 种方法:getControlvs
、getControlnc
和 getControltr
。但是,为了调用这些方法,我需要一个单独的变量来确定要调用的方法。
这就是我现在尝试调用的内容:
{% set neutPer = key.getControl~neutFaction %}
其中 neutFaction
可以是 "vs"、"nc" 或 "tr"。
这似乎只触发了 key.getControl 然后就是这样,连接丢失了。
有什么想法吗?
提前致谢!
尝试{% set neutPer = (key.getControl~neutFaction) %}
或者您可以在将变量传递给 twig 的 controller/service 中更改此设置,这样您就不需要设置串联。
您可以使用 attribute twig function:
首先将字符串连接为:
{% set method = "getControl" ~ neutFaction %}
然后调用为
{{ attribute(key, method) }}
您也可以将参数传递为:
{{ attribute(key, method, arguments) }}
此外,定义的测试可以检查是否存在动态属性:
{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}