Twig Variable Variables for a method(方法的 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 个方法: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) }}
您也可以将参数传递为:
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' }}
这篇关于方法的 Twig 变量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:方法的 Twig 变量变量


基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01