1

Suppose that in a Twig template, I want to print the first value of a multi-value field, then something else, and finally all other values of the same field. Is there a way to do that?

I know how to get the first value of the field, but I don't know how to exclude that first value from the place where I'm printing all other values.

This is what I tried, but doesn't work:

{# print first field value #}
{{ content.field_foo.0 }}
{# print something else #}
<hr>
{# print remaining field values #}
{{ content.field_foo|without(0) }}

Alternatives for the last line that didn't work either:

{{ content.field_foo|without('0') }}
{{ content.field_foo|without('field_foo.0') }}

Looking at the code in twig_without(), I would expect {{ content.field_foo|without(0) }} to work, but instead the entire field disappears.

1
  • Try to use slice filter. Like this: {% set rows = rows|slice(1) %}. So basically just create new variable and remove one element from previous array Commented Feb 5, 2019 at 12:20

1 Answer 1

4

In field preprocessing this while loop which fills the field items doesn't get started if the first delta is removed:

  $delta = 0;
  while (!empty($element[$delta])) {
    $variables['items'][$delta]['content'] = $element[$delta];
    $delta++;
  }

So if you bypass the field template to print the 0 delta do the same with the other deltas:

{# print first field value #}
{{ content.field_foo.0 }}
{# print something else #}
<hr>
{# print remaining field values #}
{% for key, item in content.field_foo if key > 0  %}
  {{ item }}
{% endfor %}
1
  • Thank you, and extra kudos for figuring out where exactly field preprocessing says "no" ;-) It must be noted that there is a downside to this solution: you lose the field wrapping div in the process. (I tried an alternative method to avoid that: {% set remaining_foo = content.field_foo|merge({0: []}) %} {{ remaining_foo }} but that didn't work.) Commented Feb 6, 2019 at 17:45

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.