我想做以下代码:
{% 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....
简短回答:not 直接/原生 possible…然而。
显然,他们在Twig 1.2中添加了一个名为attribute()的新函数,正好满足了这个需求。
但到目前为止,你只能下载Twig 1.1.2;所以1.2可能没有随SF2一起发布——尽管我找不到版本号。
我试图用不同的技巧来解决这个问题,但无济于事;1.2会修复它。
1.2新版功能:属性函数在Twig 1.2中添加。
属性可以用来访问变量的"动态"属性:
{{ 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' ]
树枝>:{% set x = "a" %}
{{ obj.getValueForKey(x) }}
将输出'1'
使用括号语法:bldg[key]
我编写了自己的分支扩展来做到这一点。你可以按我想要的方式使用它:
{% set keyVariable = 'propertyName' %}
{{ obj.access(keyVariable) }}
{# the above prints $obj->propertyName #}
// filename: Acme/MainBundle/Extension/AccessTwigExtension.php
namespace AcmeMainBundleExtension;
class AccessTwigExtension extends Twig_Extension
{
public function getFilters()
{
return array(
'access' => new Twig_Filter_Method($this, 'accessFilter'),
);
}
public function getName()
{
return 'access_twig_extension';
}
// Description:
// Dynamically retrieve the $key of the $obj, in the same order as
// $obj.$key would have done.
// Reference:
// http://twig.sensiolabs.org/doc/templates.html
public function accessFilter($obj, $key)
{
if (is_array($obj)) {
if (array_key_exists($key, $obj)) {
return $obj[$key];
}
} elseif (is_object($obj)) {
$reflect = new ReflectionClass($obj);
if (property_exists($obj, $key) && $reflect->getProperty($key)->isPublic()) {
return $obj->$key;
}
if (method_exists($obj, $key) && $reflect->getMethod($key)->isPublic()) {
return $obj->$key();
}
$newKey = 'get' . ucfirst($key);
if (method_exists($obj, $newKey) && $reflect->getMethod($newKey)->isPublic()) {
return $obj->$newKey();
}
$newKey = 'is' . ucfirst($key);
if (method_exists($obj, $newKey) && $reflect->getMethod($newKey)->isPublic()) {
return $obj->$newKey();
}
}
return null;
}
}
要在我的程序中使用它,我还必须在依赖注入中添加几行:
//filename: Acme/MainBundle/DependencyInjection/AcmeMainInjection.php
// other stuff is here....
public function load(array $configs, ContainerBuilder $container)
{
// other stuff here...
$definition = new Definition('LadMainBundleExtensionAccessTwigExtension');
$definition->addTag('twig.extension');
$container->setDefinition('access_twig_extension', $definition);
// other stuff here...