Score:0

How to add index to paragraph template

af flag

I want to use paragraphs to implement a carousel, and for now, I have the outer paragraph called slideshow, and the template is paragraph--slideshow.html.twig. Then, inside this paragraph, I can add slides, and the template is paragraph--slide.html.twig.

At the moment, I only have the default paragraphs template which looks like this:

{%
  set classes = [
    'paragraph',
    'paragraph--type--' ~ paragraph.bundle|clean_class,
    view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
    not paragraph.isPublished() ? 'paragraph--unpublished'
  ]
%}

{% block paragraph %}
  <div{{ attributes.addClass(classes) }}>
    {% block content %}
      {{ content }}
    {% endblock %}
  </div>
{% endblock paragraph %}

Problem: When I view the page in the front-end, all slide divs have the exact same properties.

Question: How do I count a display the number of paragraphs of the same type? Is there a way to add indexing?

The html should look like this:

<div class="paragaph-1 other_classes"></div>
<div class="paragaph-2 other_classes"></div>
<div class="paragaph-3 other_classes"></div>
<div class="paragaph-4 other_classes"></div>
leymannx avatar
ne flag
You have to look what's inside `{{ content }}`. Install the Twig Tweak module and then print `{{ dd() }}` inside your template. The slides are probably somewhere in `{{ content.field_slides|field_value }}` or similar. Get the field items, loop, build the markup and attach libraries as you need it. Maybe enable Twig debugging first. Read https://www.drupal.org/docs/theming-drupal/twig-in-drupal/discovering-and-inspecting-variables-in-twig-templates and https://www.drupal.org/docs/theming-drupal/twig-in-drupal/debugging-twig-templates.
4uk4 avatar
cn flag
Yes, this is one way, but bypassing the field template can have some unwanted side-effects. Better render `{{ content }}` as it is and use the resulting field template to output the index and adjust the CSS to the template structure. See https://drupal.stackexchange.com/questions/244152/getting-index-of-item-in-items-inside-twig-template
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.