1

I am trying to get data index for accordion items using scriban in sitecore sxa. Below is my scriban code.

<div class="accordion accordion-flush" id="accordionFlushExample">
  {{ for childItem in i_item.Children }}
  {{ if childItem }}
  <div class="accordion-item">
    <h2 class="accordion-header" id="flush-heading-{{childItem.name  | string.replace ' ' '' }}">
      <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapse-{{childItem.name  | string.replace ' ' '' }}" aria-expanded="false" aria-controls="flush-collapse-{{childItem.name  | string.replace ' ' '' }}">
        {{ sc_field childItem 'Heading' }}
      </button>
    </h2>
    <div id="flush-collapse-{{childItem.name  | string.replace ' ' '' }}" class="accordion-collapse collapse show" aria-labelledby="flush-heading-{{childItem.name  | string.replace ' ' '' }}" data-bs-parent="#accordionFlushExample" data-item-index="{{i_childItem.index}}">
      <div class="accordion-body">
        {{ sc_field childItem 'Content' }}
      </div>
    </div>
  </div>
  {{ end }}
  {{ end }}
</div>
2
  • I'd guess {{ for x in 0..i_item.Children.size-1 }} and then using i_item.Children[x] instead of childItem in the code below.
    – Mark Cassidy
    Commented Apr 19 at 10:55
  • Do you need an index in a for loop or you want to use search functionality in Sitecore index?
    – Marek Musielak
    Commented Apr 24 at 14:28

2 Answers 2

1

In Scriban, you can achieve this by using the {{ for i in ... }} syntax, where i represents the index of the current item in the loop. Here's how you can modify the loop to use the index:

<ul>
{{ for i in (0..item.Children.size-1) }}
    {{ $child = item.Children[i] }}
    <li>{{ $child.Name }}</li>
{{ end }}
</ul>

Here you can find more information about Scriban loops: https://github.com/scriban/scriban/blob/master/doc/language.md#95-loops

1

You can use {{for.index}} helper as in below code, to get index inside foreach iteration in Scriban.

<div class="accordion accordion-flush" id="accordionFlushExample">
 {{ for childItem in i_item.Children }}
 <div index="{{for.index}}"> 
 </div>
 {{ end }}
</div>

You can find details of more helper functions here:

  1. {{for.rindex}} - The current index of the for loop starting from the end of the list
  2. {{for.first}} - A boolean indicating whether this is the first step in the loop
  3. {{for.last}} - A boolean indicating whether this is the last step in the loop
  4. {{for.even}} - A boolean indicating whether this is an even row in the loop
  5. {{for.odd}} - A boolean indicating whether this is an odd row in the loop

Hope this helps!!!

Not the answer you're looking for? Browse other questions tagged or ask your own question.