如果在一个分支中,我有一个对象,我想测试一个名为getName的方法是否可以在该对象上调用,是否存在这种情况?
我尝试了以下操作,但没有成功:
{% if lastCategory.method(getName) is defined %}
是的,你可以这样做:
{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}
在你的例子中,它将是像
这样的东西{{ attribute(lastCategory, 'getName') is defined ? 'Method exists' : 'Method does not exist' }}
参见文档
这不是你应该在Twig模板中做的事情。注意,如果您试图访问不存在的内容,Twig永远不会抛出错误。foo.bar
是一个Twig表达式,翻译成比$foo->bar()
复杂得多的东西。你的模板应该是这样的:
{{ lastCategory.name }}
这几乎涵盖了所有的理由:
-
lastCategory
为数组,name
为索引 -
lastCategory
是一个对象和-
name
是一个属性 -
name
是一个方法 -
getName
是一个方法 -
isName
是方法
-
- 以上都不输出,在这种情况下没有输出
即使foo.bar.this.does.not.exist
也永远不会抛出错误,它什么都不做。
如果需要进行测试,只需执行:
{% if lastCategory.name %}
如果你想避免调用该方法两次(尽管这将是糟糕的对象设计):
{% set name = lastCategory.name %}
{% if name %}
或者你正在寻找这个习语:
{{ lastCategory.name|default('No name') }}
试试这个: {% if lastCategory.name is defined %}
。
创建Twig Extension并在模板{% if method_exists(lastCategory, 'getName') %}Yes{% else %}No{% endif %}
中使用
<?php
namespace AppBundle'Twig;
class SomeTwigExtension extends 'Twig_Extension {
public function getFunctions()
{
return array(
'method_exists' => new 'Twig_SimpleFunction('method_exists', array($this, 'isMethodExist'))
);
}
public function isMethodExist($object, $method)
{
return method_exists($object, $method);
}
public function getName()
{
return 'method_exists_twig_extension';
}
}
我使用答案作为基础,而不是return method_exists($object, $method);
,我使用return isset($object->$method);
,例如第一个变量总是因未知原因返回false。