我想执行以下代码:
{% set rooms = [] %}
{% set opts = {
'hasStudio': 'Studio',
'has1Bed': '1 BR',
'has2Bed': '2 BR',
'has3Bed': '3 BR',
'has4BedPlus': '4 BR+'
}
%}
{% for key, val in opts %}
{% if bldg.{key} is none %} {# PROBLEM HERE.. HOW TO FIND THIS MEMBER!? #}
{{ val }}?
{% elseif bldg.{key} %}
{{ val }}
{% else %}
No {{ val }}
{% endif %}
{% endfor %}
如何调用以key
的值命名的bldg的成员属性?我想获得值
bldg.hasStudio
bldg.has1Bed
bldg.has2Bed
etc....
最佳答案
简短的回答:还不是直接/原生可能......但是。
显然他们在 Twig 1.2 中添加了一个名为 attribute() 的新函数这恰恰满足了这一需求。
但到目前为止,您只能下载 Twig 1.1.2;所以 1.2 可能没有随 SF2 一起提供——尽管我找不到版本号。 (1.2 现已可用!)
我尝试用不同的技巧来解决这个问题,但无济于事; 1.2 将修复它。
New in version 1.2: The attribute function was added in Twig 1.2.
attribute can be used to access a “dynamic” attribute of a variable:
{{ attribute(object, method) }}
{{ attribute(object, method,arguments) }}
{{ attribute(array, item) }}
但是您可以做的是在您的类中添加一个方法来处理您需要的任何事情。类似的东西:
php:
class C
{
public $a = 1;
public $b = 2;
public function getValueForKey($k)
{
return $this->$k;
}
}
[ providing an instance of C to the template as 'obj' ]
Twig :
{% set x = "a" %}
{{ obj.getValueForKey(x) }}
将输出'1'
关于php - 如何访问由变量确定的 Twig 成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7378975/