You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 17:15:33