Symfony5/Twig中如何检查路由参数未定义/未设置?
解决Symfony5/Twig路由可选参数的菜单项高亮问题
问题原因
你遇到的错误是因为当路由未传递type参数时,app.request.attributes.get('type')返回null,此时直接访问.id属性会触发Twig的空变量属性访问错误。之前用is defined无效的原因是:即使参数值为null,is defined仍会返回true(因为该参数键在attributes中存在),无法阻止后续的属性访问操作。
解决方案
1. 使用Twig空安全操作符(推荐)
Twig 2.10+(Symfony5默认集成的版本支持)提供了?->空安全访问操作符,当变量为null时会直接返回null,不会抛出错误。修改判断条件如下:
<li> <a class="{% if app.request.get('_route') == 'app_support_case_new' and app.request.attributes.get('type')?->id == 1 %}active{% endif %}" href="{{ path('app_support_case_new', {'type':1}) }}"> <span class="glyphicon glyphicon-plus glyphicon-user" aria-hidden="true"></span> Staff <i class="glyphicon glyphicon-random opacity50"></i> </a> </li>
同理,第二个带type=2的菜单项也用同样方式修改即可。
2. 显式判断变量不为null
如果需要兼容更低版本的Twig,可以先判断type变量不为null,再访问其id属性:
<li> <a class="{% if app.request.get('_route') == 'app_support_case_new' and app.request.attributes.get('type') is not null and app.request.attributes.get('type').id == 1 %}active{% endif %}" href="{{ path('app_support_case_new', {'type':1}) }}"> <span class="glyphicon glyphicon-plus glyphicon-user" aria-hidden="true"></span> Staff <i class="glyphicon glyphicon-random opacity50"></i> </a> </li>
3. 优化模板代码(可选)
可以将路由判断逻辑抽离为变量,减少重复代码,提升模板可读性:
{% set isNewCaseRoute = app.request.get('_route') == 'app_support_case_new' %} <li> <a class="{% if isNewCaseRoute and app.request.query.get('type') is not defined %}active{% endif %}" href="{{ path('app_support_case_new') }}"> <span class="glyphicon glyphicon-plus glyphicon-plus" aria-hidden="true"></span> No topic </a> </li> <li> <a class="{% if isNewCaseRoute and app.request.attributes.get('type')?->id == 1 %}active{% endif %}" href="{{ path('app_support_case_new', {'type':1}) }}"> <span class="glyphicon glyphicon-plus glyphicon-user" aria-hidden="true"></span> Staff <i class="glyphicon glyphicon-random opacity50"></i> </a> </li> <li> <a class="{% if isNewCaseRoute and app.request.attributes.get('type')?->id == 2 %}active{% endif %}" href="{{ path('app_support_case_new', {'type':2}) }}"> <span class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> Order </a> </li>
内容的提问来源于stack exchange,提问作者Matt Welander
相关产品推荐
相关产品推荐

