0

In my paragraph twig file paragraph--call-to-actions.html.twig, I want to render and build up the entity reference items (the child items from a certain Paragraph type).

There could be 3 or 4 items. Based on the length of the items (3 or 4) I want to change the markup/change a CSS class so I could have 3 or 4 columns.

In paragraph--call-to-actions.html.twig I could do something like:

{% if content.field_call_to_actions|length == 3 %}
  {# Build 3 column item markup here #}
{% elseif content.field_call_to_actions|length == 4 %}
  {# Build 4 column item markup here #}

But how do I loop through my entity reference items (Paragraph type items) so I can print all of the fields of my paragraph type?

Or is there a cleaner approach?

Update: I found a solution by extending field.html.twig to field--paragraph--call-to-actions.html.twig and in there:

{% for item in items %}

  <div class="card mx-6 md:mx-4 mb-6 md:mb-0
  {% if items|length == 3 %}
    md:w-1/3
  {% elseif items|length == 4 %}
    md:w-1/2 lg:w-1/4
  {% endif %}
  ">
    {{ item.content }}
  </div>

{% endfor %}

I can't use loop.lenght here because of the different breakpoints.

Can I write this more cleaner without duplicate classes (DRY)?

0
{% for action in paragraph.field_call_to_actions %}
    {{ paragraph.action.value }}
{% endfor %}
| improve this answer | |
  • I found a solution and update my question. With your suggestion I couldn't get the fields visible? Is this a good approach? – meez Apr 26 at 6:00
0

My suggestion is to use the Twig Field Value module.

{% for action in paragraph.field_call_to_actions %}
    {{ paragraph.action|field_value }}
{% endfor %}

or

{% for action in paragraph.field_call_to_actions %}
    {{ paragraph.action|field_value|render }}
{% endfor %}
| improve this answer | |
0

I found a solution by extending field.html.twig to field--paragraph--call-to-actions.html.twig and in there:

{% for item in items %}

  <div class="card mx-6 md:mx-4 mb-6 md:mb-0
  {% if items|length == 3 %}
    md:w-1/3
  {% elseif items|length == 4 %}
    md:w-1/2 lg:w-1/4
  {% endif %}
  ">
    {{ item.content }}
  </div>

{% endfor %}
| improve this answer | |

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.