1

I'm currently using Drupal Views and I'm trying to figure how to check the first item/content on the view. On a twig template I could write

{% for items in related_content.entity.field_content_items %}

    {% if loop.first %}

    first element

    {% endif %}

{% endfor %}

I tried writing the same condition within the view using {% if loop.first %} but it doesn't work. Is there similar code to achieve this within Drupal Views Custom Text

1 Answer 1

2

Have you tried to print other stuff of the loop variable, maybe {{ loop.index }}, did this work? You then could if-request this. As far as I remember loop.index worked fine in Drupal.

Next thing you can try is to iterate over the keys and if-request the key for your logic. Pretty much the same as loop.index.

{% for key, items in related_content.entity.field_content_items %}
  {% if key == 0 %}

Last resort would be to target related_content.entity.field_content_items[0] directly.

But I think the first two suggestions should give you at least one opportunity to do what you want.


Thanks for the clarification. Views custom text only. OK, in that case consider to use 2 views (or just 2 displays of the same view) as outlined here https://drupal.stackexchange.com/a/104608. Then you'd attach the first view (or display) - which is limited to display only 1 row - before your second view (there must be an attachment option somewhere) and your second view then should be configured to have an offset of 1.

4
  • Just to clarify I'm using Drupal 8 views custom text. I believe the looping syntax you have provided is for twig templates imgur.com/a/JUOIOKB
    – clestcruz
    Commented Jul 17, 2018 at 7:09
  • @clestcruz – In that case consider to use 2 views (or just 2 displays of the same view) as outlined here drupal.stackexchange.com/a/104608. Then you'd attach the first view (or display) - which is limited to display only 1 row - before your second view (there must be an attachment option somewhere) and you second view then has an offset of 1.
    – leymannx
    Commented Jul 17, 2018 at 8:27
  • I see, there is no syntax in detecting the first content/item.
    – clestcruz
    Commented Jul 17, 2018 at 8:29
  • 1
    @clestcruz – Maybe no. But there's the Views attachment before/after thing. And there might be some Views header/footer thing if I remember it right. So, depending on what exactly you want to output there, these might become pretty handy :)
    – leymannx
    Commented Jul 17, 2018 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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