0

If I use any loop in Drupal, I can get loop.index to get the index of looped item. - Ref#1

For example -

    {% for tag in content.some_array %}
      <div class="item-count-{{loop.index}}">{{ tag.content }}</div>
    {% endfor %}

This is a field containing paragraph type -

field--field-container.html.twig

and its content is {{items}} ({{items|length}} gives the desired count)

The above template iterate through it's items and include the following template multiple times- paragraph--multiple-blocks.html.twig and its html is

    <div class="multiple-blocks multiple-block-count-{{loop.index}}">
    =====CONTENT=====
    </div>

But I cannot get the loop.index (Ref#1) in the paragraph--multiple-blocks.html.twig template. I tried (surely google search shows all links visited) kint() debugging but could not get anything related to the count or index of the item iterated.

I will be grateful to any guide/help (don't want to code in PHP) close to get this done in twig files will.

1

You can't, because the loop index is local. And you don't need a class with the index in the paragraph when you have it in the surrounding div for targeting it in CSS.

There is also a fundamental aspect with rendering referenced entities. They are cached and not necessarily rebuild when the order in the field changes. This is even more problematic for other entities than paragraphs, which can be used in more than one place in different orders.

  • Thank you for your quick reply. Is there any other work around so that I can retain the current structure and get the index. – Vishal Kumar Sahu Aug 19 '17 at 12:10
  • I tried to explain why referenced entities like paragraphs are unaware of their position in the field and that there are many reasons not to try to make them aware. And that probably you don't need this, because CSS can work with the structure as it is. – 4k4 Aug 19 '17 at 13:09
  • There are other solution, JS/CSS or even tweaking with PHP in Drupal. But doing it in twig way would have been even better solution. :-) – Vishal Kumar Sahu Aug 19 '17 at 16:11
  • 1
    I wouldn't say you need tweaking with CSS. You simply can target any element in the paragraph, which is inside of the field div with the indexed class. – 4k4 Aug 19 '17 at 16:34
  • I think that should be default thing to index everything whatever is being looped... Anyway I am going for different approach to achieve these things... – Vishal Kumar Sahu Aug 23 '17 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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