Quick Drupal 8 Theming Tips

By Kevin Quillen, on January 13, 2017

If you are theming an entity (in this case, node) and you want to display the created or changed date in a different format, you can use the following to do just that. In my case, I am creating a couple of view modes with their respective twig templates and need to show post dates in a few different formats.

Use getCreatedTime to fetch the node created date, and use format_date against it, supplying a date format machine name:


{{ node.getCreatedTime|format_date('homepage_article') }}

The same works for changed, too, with getChangedTime:


{{ node.getChangedTime|format_date('last_changed') }}

Granted, you could install modules like Display Suite to expose these as ‘extra fields’ in the display and adjust the formatting options, but I am running my first Drupal 8 projects as lean and mean as possible.

Here is another case. Perhaps you have a component that is wrapped entirely in a link. This would mean that you can’t really rely on the field formatter to do the job, because this field wraps any other field and links to the destination. This would be a common case for a call to action block type, for example, or a card component. Maybe it just links to the node - lets look at both cases.

Linking to a node:


<a href="{{ path('entity.node.canonical', {'node': node.id}) }}">
  // other fields/markup and output in between
  {{ content.field_image }}
  {{ content.field_description }}
</a>

Linking from a field value:


<a href="{{ content.field_link.0.value['#url']}}">
  {{ content.field_image }}
  {{ content.field_description }}
</a>

The second one isn’t particularly clean, although I haven’t seen a consensus on if it is better to preprocess and inject new variables or to just do it this way.

There are more useful twig filters listed on the Drupal theming docs page.

Tagged with: twig, theming
comments powered by Disqus