Twig Variable 方法的变量 [英] Twig Variable Variables for a method
问题描述
我正在尝试做一些在 PHP 中很容易但在 twig 中不太容易的事情.
I'm attempting to do something that was very easy in PHP, but not so easy in twig.
基本上,我需要调用一个类方法,但我需要能够定义通过字符串调用的方法.
Basically, I need to call a class method, but I need to be able to define the method to call via a string.
我有 3 个方法:getControlvs
、getControlnc
和 getControltr
.但是,为了调用这些方法,我需要一个单独的变量来确定要调用哪个.
I have 3 methods: getControlvs
, getControlnc
and getControltr
. However, in order to call these methods, I need a seperate variable which determines which one to call.
这就是我现在试图调用的:
This is what I'm attempting to call right now:
{% set neutPer = key.getControl~neutFaction %}
其中 neutFaction
可以是vs"、nc"或tr".
Where neutFaction
can be either "vs", "nc", or "tr".
这似乎只是触发 key.getControl 然后就是这样,连接丢失了.
This only seems to fire key.getControl and then that's it, the concatenation is lost.
有什么想法吗?
提前致谢!
推荐答案
您可以使用 属性树枝函数:
首先将字符串连接为:
{% set method = "getControl" ~ neutFaction %}
然后调用为
{{ attribute(key, method) }}
你也可以传递参数:
{{ attribute(key, method, arguments) }}
此外,定义的测试可以检查动态属性的存在:
In addition, the defined test can check for the existence of a dynamic attribute:
{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}
这篇关于Twig Variable 方法的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!