Drupal 8 – Formatting a Date Field in Twig

Here are the four easiest ways I’ve found to show dates via Twig inside of a node template.

They all result in the same output.

Use the field’s formatter settings; include wrappers

This is the only example that includes wrappers. The rest output just the date.

 

Use the field’s formatter settings

This will use the format defined in Content type » Manage Displays » Your View Mode.

 

Use Twig date filter + a defined Drupal date format

I have defined, via the Drupal UI, a date format. Here’s the config for it:

uuid: 1a50c79f-96df-45de-9a21-32e0d8327806
langcode: en
status: true
dependencies: { }
id: short_mdyyyy
label: 'Short - m/d/yyyy'
locked: false
pattern: n/j/Y

 

Use Twig date filter

Tagged with: , ,
Posted in Development
One comment on “Drupal 8 – Formatting a Date Field in Twig
  1. Quentin says:

    {% set finPromo = node.field_fin_prix_special.value|date(‘d M Y’) %}
    {% set today = “now”|date(‘d M Y’) %}

    {% if content.field_fin_prix_special|render %}

    {% if finPromo < today %}
    {{ content.field_prix_special }}
    Fin de promo le {{ content.field_fin_prix_special.0 }}

    {% else %}

    {{ content.field_prix }}
    {% endif %}
    {% endif %}

    How i can compare 2 date in Template ? and what it return me the date of today for my field date custom
    thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

*