Twig/Symfony 2 中的 Instanceof 运算符? [英] Instanceof operator in Twig/Symfony 2?
本文介绍了Twig/Symfony 2 中的 Instanceof 运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的混合数组(手机号码和实体):
I've a mixed array like this one (mobile numbers and entities):
$targets = array();
$targets[] = '+32647651212';
$targets[] = new Customer();
在我的 Twig 模板中,如果 target
是 Customer
,我必须调用 getMobile()
或者如果它实际上是一个数字,则只打印数字(string
).
In my Twig template i have to call getMobile()
if target
is a Customer
or just print the number if it's actually a number (string
).
Twig 中是否有类似 instanceof
的操作符?
Is there something like instanceof
operator in Twig?
<ul>
{% for target in targets %}
<li>{{ target instance of MyEntity ? target.getMobile : target }}</li>
{% else %}
<li>Nothing found.</li>
</ul>
推荐答案
在 \Twig_Extension 中你可以添加测试
In \Twig_Extension you can add tests
public function getTests()
{
return [
'instanceof' => new \Twig_Function_Method($this, 'isInstanceof')
];
}
/**
* @param $var
* @param $instance
* @return bool
*/
public function isInstanceof($var, $instance) {
return $var instanceof $instance;
}
然后像这样使用
{% if value is instanceof('DateTime') %}
这篇关于Twig/Symfony 2 中的 Instanceof 运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文