Add loop index in paragraph.html.twig

Created on 25 May 2017, over 7 years ago
Updated 10 August 2023, over 1 year ago

The paragraph.html.twig template file doesn't have the current loop index available to it, so we have no idea what item is currently being rendered - it is useful sometimes to know what the index is, as we might want to set some different css classes or similar on specific indexes.

To work around this, I added a field hook in my template:

function mytheme_preprocess_field(&$variables) {
    if($variables['field_name'] == 'my_paragraph_field'){

     foreach($variables['items'] as $idx => $item) {
        $variables['items'][$idx]['content']['#paragraph']->index = $idx;
      }
    }
}

This enables me to access the index in the twig template using paragraph.index, but it would be preferable if this or something similar was available natively.

✨ Feature request
Status

Active

Version

1.0

Component

Code

Created by

πŸ‡¬πŸ‡§United Kingdom brynj

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024