I have a node content type with a paragraph field with multiple values. The paragraph has a date and a text field. When I display the node, I'd like to sort the paragraph values by date. I've tried doing this in twig with the sort filter to no avail. Can this be done somehow, maybe with preprocessing the field?

1 Answer 1


This should be no problem sorting the field items in preprocessing the field, but since Drupal 9 this can also be done in Twig.

For example:


{% set items = items|sort((a, b) => a.content['#paragraph'].field_date.date.gettimestamp() <=> b.content['#paragraph'].field_date.date.gettimestamp()) %}

See the Twig 2.x docs (available for Drupal >=9): https://twig.symfony.com/doc/2.x/filters/sort.html

If the .date property doesn't work it's a different field type. Try the generic .value property:

{% set items = items|sort((a, b) => a.content['#paragraph'].field_foo.value <=> b.content['#paragraph'].field_foo.value) %}

This also applies to the Timestamp field type. Not often used for configured fields, most times for base fields like Created or Changed.

  • Thanks - I was trying something similar, but couldn't get it to work. The date field in my paragraph type is called field_dw_date, so my sort looks like this: % set items = items|sort((a, b) => a.content['#paragraph'].field_dw_date.date.gettimestamp() <=> b.content['#paragraph'].field_dw_date.date.gettimestamp()) %}. It isn't working though, I don't understand how the fields are dereferenced. What does date mean in .field_dw_date.date ?
    – pglatz
    Commented May 14, 2022 at 17:42
  • 1
    See drupal.stackexchange.com/questions/252333/…
    – 4uk4
    Commented May 14, 2022 at 23:18
  • Good to know, thanks.
    – pglatz
    Commented May 15, 2022 at 0:47

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.