How to display in twig node creation date yesterday / today format in drupal 8 / 9


The “today / yesterday” format is still relevant today. So let’s try to implement it in Drupal 8/9. As you know, version 9 of Drupal received a new version of the Twig template engine – 2.1. Because of this, the logic and syntax of working with templates have changed a bit. At first I thought that this would not pose any problems, but after having studied most of the materials on this topic, I did not find very scant information, and even then for version 7 of Drupal.

After some experimentation, I got the following code (working).

For work with Views example:

{% if created.value|date("d/m/Y")  == "today"|date("d/m/Y") %} 
{% elseif  created.value|date("d/m/Y")  == "yesterday"|date("d/m/Y") %}
{% endif %}

Note: Do not use the date format with hours and minutes as the default values for “yesterday” and “today” are “ : 00:00”.And your comparison operation will always be wrong

Work with twig template. Example: node.html.twig

   {% if node.created.value|date("d F Y")  == 'today'|date("d F Y") %}
    {% elseif node.created.value|date("d F Y")  == 'yesterday'|date("d F Y") %}
    {% endif %}

That’s all. Hope you find this helpful. Happy coding!

Similar Posts:


How useful was this post?

Click on a star to rate it!

Average rating 4.5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

Scroll to Top