n Drupal 8 - Add loop index in paragraph.html.twig | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

in this post, i'll show you how to add loop index in paragraph.html.twig using hook_preprocess_field(&$variables){}

/**
 * @param $variables
 */
function mytheme_preprocess_field(&$variables) {
  if($variables['field_name'] == 'field_paragraph_name'){
    foreach($variables['items'] as $idx => $item) {
      $variables['items'][$idx]['content']['#paragraph']->index = $idx;
    }
  }
}

and then in your paragraph.html.twig file you can use {{ paragraph.index }}

{% if paragraph.index == 0 %}
  <li class="accordion-item is-active">
{% else %}
  <li class="accordion-item">
{% endif %}

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook