Twig:在if条件下过滤

时间:2013-03-07 22:35:23

标签: symfony twig

我想在Twig的if条件中使用过滤器。原因是Symfony2属性,我无法直接比较,我必须事先更改它。我已经开始使用此代码:

{% if app.request.attributes.get('_controller')|split('::')|first == 'some\controller\name' %}
  do something
{% endif %}

不幸的是,这不起作用。所以我想我会在比较之前使用set:

{% set controller = app.request.attributes.get('_controller')|split('::')|first %}
{% if controller == 'some\controller\name' %}
  do something
{% endif %}
{{ controller }} {# would print 'some\controller\name' #}
猜猜是什么? "做点什么"即使变量 controller 现在存在并且具有我与之比较的值,也不会打印。我做错了什么?

1 个答案:

答案 0 :(得分:3)

好的我测试过,Twig有一种奇怪的行为。 “\”被转义或类似的东西。 我使用var_dump函数扩展了我的twig environement,请检查:

{{ var_dump("Sybio\Bundle\WebsiteBundle\Controller\MainController") }}
//string(48) "SybioBundleWebsiteBundleControllerMainController"

{{ var_dump(app.request.attributes.get('_controller')|split('::')|first) }}
// string(52) "Sybio\Bundle\WebsiteBundle\Controller\MainController"

{{ var_dump("Sybio\\Bundle\\WebsiteBundle\\Controller\\MainController") }}
// string(52) "Sybio\Bundle\WebsiteBundle\Controller\MainController"

这就是为什么你的测试总是错误的。 你需要加倍比较字符串的反斜杠......

{% if app.request.attributes.get('_controller')|split('::')|first == 'some\\controller\\name' %}
  do something
{% endif %}
相关问题