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

Symfony3 Twig路由判断显示内容异常求助

Fixing Your Twig Route-Based Content Display Code

Let's walk through the issues in your code and fix them step by step:

1. Syntax Typo in Route Condition

You have an extra f in AND f app.request.get('_route') — that's breaking the logic entirely. Replace it with AND (or Twig's preferred lowercase and for better readability).

2. Unclosed Div Tag

Your opening <div class="preview-list-element-content-visual-default"> wasn't properly closed. The closing </div> needs to sit right after the else branch's image tag, not after the outer {% endif %}.

3. Cleaned-Up Logic Structure

I've rearranged the code to make nesting clearer, which helps avoid future syntax mistakes and improves maintainability.

Corrected Code

{% if visual|default %} 
    {{- wc_simple_visual(visual) -}} 
{% else %} 
    <div class="preview-list-element-content-visual-default">
        {# Display image based on current route #}
        {% if app.request.get('_route') != 'live' and app.request.get('_route') != 'contact' %}
            <img src="/{{ asset_version('img/live-image.jpg') }}" alt="{{ title|default('') }}" class="default-image">
        {% else %}
            <img src="/{{ asset_version('img/contact-image.jpg') }}" alt="{{ title|default('') }}" class="default-image">
        {% endif %}
    </div> {# Close the default visual container here #}
{% endif %}

Small Quality-of-Life Improvements

  • Used title|default('') for the alt attribute to avoid empty alt text if title is undefined — this replaces the messy nested {% if title %} check.
  • Switched to lowercase and to match Twig's conventional coding style.
  • Added a comment to clarify the route logic for anyone reading the code later.

Test this code, and it should now correctly render the wc_simple_visual component when visual is present, or show the appropriate default image based on the current route.

内容的提问来源于stack exchange,提问作者Yan Dbz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:29:30