0

I'm trying to get the number of paragraphs an authenticated user inputs by counting them in the parent block template and trying to access that number in the paragraphs template. I have two templates I'm working with:

  1. field--field-hover-image-block.html.twig
  2. paragraph--hover-images.html.twig

The paragraphs are being loaded through the paragraph entity field in a custom block. I'm counting the number of the block paragraph fields with this code in that block's template, field--field-hover-image-block.html.twig:

{% for item in items %}
    {% set count = items|length %}
    <figure class="hover-image">{{ item.content }}</figure>
{% endfor %}

The count works, but doesn't pass to the paragraphs template.

If the count is 4 or more, I need the paragraphs template to render a class for that. Else, I don't need the class. Here is my code for the paragraphs template (paragraph--hover-images.html.twig):

{% if count >= 4 %}
   {{ content.field_hover_image.0 }}
   <figcaption class="four-count-plus">
        <div>
            <h2>{{ content.field_hover_title.0 }}</h2>
            <p>{{ content.field_hover_text.0 }}</p>
        </div>
   </figcaption>          
{% else %}
   {{ content.field_hover_image.0 }}
    <figcaption>
        <div>
           <h2>{{ content.field_hover_title.0 }}</h2>                  
           <p>{{ content.field_hover_text.0 }}</p>
         </div>
   </figcaption>
{% endif %} 

Any help with this would be greatly appreciated.

1 Answer 1

0

The count needs to be in the custom block's paragraph field twig, not the paragraph twig.

In the field--field-hover-image-block.html.twig, this works:

{% set count = 0 %}

{% for item in items %}
   {% set count = items|length %}
   {% set figure_classes = [
      'hover-image-effect',
       'image-count-' ~ count
    ] | sort | join(' ') | trim %}

    <figure class="{{ figure_classes }}">{{ item.content }}</figure>

{% endfor %}

And then in paragraph--hover-images.html.twig, format as usual:

{% block paragraph %}
    
      {% block content %}
    
        {{ content.field_hover_image.0 }}

         <figcaption class="absolute block left-0 right-0 w-full cursor-pointer">
            <div class="border-wrapper">
                 <h2 class="m-0 font-bold capitalize text-blue-500 leading-tight">{{ content.field_hover_title.0 }}</h2>
                 <p class="text-blue-500 leading-tight">{{ content.field_hover_text.0 }}</p>
                 <a href="{{ content.field_hover_link.0['#url'] }}" title="Go to {{ content.field_hover_link.0['#title'] }}" >{{ content.field_hover_link.0['#title'] }}</a>
            </div>
         </figcaption>
    
   {% endblock %}
    
{% endblock paragraph %}

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.