Symfony3 Twig路由判断显示内容异常求助
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 thealtattribute to avoid empty alt text iftitleis undefined — this replaces the messy nested{% if title %}check. - Switched to lowercase
andto 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

