4

I have created a field with unlimited number of values allowed. Now, using view I want to display all even number items (like 2nd, 4th, 6th and so on). How can I do that?

My thought: May be I need to edit views-view-field.html.twig file. But I'm not finding any way to display items in field instead of complete field. Please help me.

View source of views-view-field.html.twig:

{{ output -}}

  • You can override the individual field template and only print the even items in twig – Shreya Shetty Dec 12 '16 at 12:54
3

The standard field handler in Views returns flat rendered output. To change this or put in the feature for even/odd numbered values you would need to implement a field handler plugin. For this task that would be a bit too much work. You can improvise in theming to get the same result.

In Views you can define a separator for multiple field values. Choose a separator that is not in the content of the field. Default is ','.

In Twig you can use the filter split to get the array items. Use the separator from the multiple field settings.

views-view-field--field-fieldname.html.twig

{% set items = output|split(',') %}

Put items in a loop and display only even number items:

{% for item in items %}
  {% if loop.index is even %}
    {{ item }}
  {% endif %}
{% endfor %}
  • I tried this solution for a similar issue. I think it's worth noting that the |split() filter will provide you with markup, so you will likely need to apply a |raw filter on the item; eg. {{ item|raw }} – RominRonin Aug 2 '17 at 11:29

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.