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

如何基于数组索引修改Twig轮播的Banner按钮文本

How to Adjust Button Text for Specific Banner Indexes in Your Twig Slideshow

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:53:10