2

Date field having multiple values. Need to format the output.

{% for item in items %}
<div{{ attributes }}>{{ item.content|date(format="F j, Y") }}</div>
{% endfor %}

item.content showing the date as updated. But not able to format the result. Got the below error,

TypeError: DateTime::__construct() expects parameter 1 to be string, array given in...

Please suggest on this issue.

1
  • Use the field formatter date options in the admin configuration of this content type.
    – Kevin
    Aug 28, 2019 at 12:04

1 Answer 1

5

In Twig, drill down to the timestamp value:

node.html.twig:

{{ content.field_name['#items'].value | date('F d, Y') }}

For a loop, do:

{% for items in content.field_name['#items'] %}
  {{ items.value | date('F d, Y') }}
{% endfor %}

field.html.twig:

{% for item in items %}
  {{ item.content["#markup"] | date('F d, Y') }}
{% endfor %}

Note: Set field format display option to plain or custom if using the field template. This field option can break your site just by someone changing the format option for the field, so use caution.

4
  • Thanks. I'm using that code in twig field template : field--node--field-date--calendar-event.html.twig (field--node--[field-name]--[content-type].html.twig). So, I tried content.field_date in the loop instead of content.field_date_field. But didn't get any result. Please advise.
    – Tamilvanan
    Jul 6, 2019 at 21:22
  • Added a field template option to the answer. Jul 6, 2019 at 22:21
  • The date field does have a custom format option as well that allows custom formatting of the field value. Jul 6, 2019 at 22:35
  • Thanks @Prestosaurus I just did it using preprocess function based on content type.
    – Tamilvanan
    Jul 23, 2019 at 13:49

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.