0

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.

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

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.

  • 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 N Jul 6 at 21:22
  • Added a field template option to the answer. – Prestosaurus Jul 6 at 22:21
  • The date field does have a custom format option as well that allows custom formatting of the field value. – Prestosaurus Jul 6 at 22:35
  • Thanks @Prestosaurus I just did it using preprocess function based on content type. – Tamilvanan N Jul 23 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.