方法的 Twig 变量变量

2022-01-22 00:00:00 php symfony twig

我正在尝试做一些在 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 个方法:getControlvsgetControlncgetControltr.但是,为了调用这些方法,我需要一个单独的变量来确定调用哪个方法.

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) }}

您也可以将参数传递为:

You can pass arguments also as:

{{ 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' }}

相关文章