如何基于数组索引修改Twig轮播的Banner按钮文本
Got it, let's tweak that button text condition in your slideshow.twig component. The key here is leveraging Twig's built-in loop variables to target the exact banner positions you want. Here's how to make it work:
Option 1: Target Visible Banner Order (1-based counting)
If you're referring to the 1st and 3rd banners as they appear in the slideshow (since loop.index starts counting at 1), use this code:
{% for banner in banners %} <div class="banner"> <!-- Your existing banner content (images, headings, descriptions, etc.) --> {% if loop.index in [1, 3] %} <button>Read More</button> {% else %} <button>Shop Now</button> {% endif %} </div> {% endfor %}
Option 2: Target Raw Array Indexes (0-based counting)
If you're referencing the actual array indexes (most languages like PHP use 0-based indexing for lists, so the 1st banner is index 0, 3rd is index 2), switch to loop.index0:
{% for banner in banners %} <div class="banner"> <!-- Your existing banner content --> {% if loop.index0 in [0, 2] %} <button>Read More</button> {% else %} <button>Shop Now</button> {% endif %} </div> {% endfor %}
Bonus: Clean, Concise Version (Great for Translations)
If you use translation filters or want cleaner code, define the button text in a variable first:
{% for banner in banners %} <div class="banner"> <!-- Your existing banner content --> {% set button_text = loop.index in [1, 3] ? 'Read More'|trans : 'Shop Now'|trans %} <button>{{ button_text }}</button> </div> {% endfor %}
Just pick the option that matches how you're referencing your banner positions—either visible order (1-based) or raw array index (0-based). This will make your 1st and 3rd banners show "Read More" while the others keep "Shop Now".
内容的提问来源于stack exchange,提问作者mcmcphillips

