alchemy-cms

Get index of element in "element_view_for" helper in Alchemy CMS


I want to use a bootstrap 5 carousel in an alchemy element with nested images. In order to do this, i need to get the sortorder or index of the iteration, as the carousel expects an "active" tag on the first element.

  <%= element_view_for(image_slide, tag: false) do |el| %>
    <div class="carousel-item active">
      <%= el.render :image, {}, class: "d-block w-100 #{"active" if index == 0}" %>
    </div>
  <% end %>

How can i achieve this?


Solution

  • In every Rails partial that rendered by the collection renderer you have a local variable called <the-partial-name>_counter available.

    From https://guides.rubyonrails.org/layouts_and_rendering.html#local-variables

    Rails also makes a counter variable available within a partial called by the collection, named after the title of the partial followed by _counter. For example, when rendering a collection @products the partial _product.html.erb can access the variable product_counter which indexes the number of times it has been rendered within the enclosing view. Note that it also applies for when the partial name was changed by using the as: option. For example, the counter variable for the code above would be item_counter.

    Just make sure that the parent element (I'm assuming an imager_slider) uses the collection partial renderer.

    [...]
      <%= render image_slider.nested_elements.published %>
    [...]
    

    Then you can use

    <%= element_view_for(image_slide, tag: false) do |el| %>
      <div class="carousel-item active">
        <%= el.render :image, {}, class: "d-block w-100 #{"active" if image_slide_counter == 1}" %>
      </div>
    <% end %>