I am trying to get different templates for events node based on the date of the event. The content type used will be same for both, ie. Event.

This is what I have done so far:
Created a content type: Event
Added a date range field: field_date

This is what I need to get:
If the date of the event is greater than the current date, template suggestion will be node--upcoming.html.twig
If the date of the event is less than the current date, template suggestion will be node--past.html.twig

I tried with the following code:

function strive_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $node = $variables['elements']['#node'];
  if ($node->getType() === 'event') {
    $date = $node->field_date->end_value ?? $node->field_date->start_value;
    $current_date = new \DateTime();
    $date = new \DateTime($date);
    $node_type_suggestion = $current_date > $date ? 'past' : 'upcoming';
    $suggestions[] = 'node__' . $node_type_suggestion;

Doing this, I am getting node--upcoming.html.twig for all the event nodes.

enter image description here

  • This isn't the best way to handle this. Even if you were to get your template suggestions working I think the template would be cached so you wouldn't see the template change without the twig/theming cache being cleared. Sounds more like you'd need a custom block/controller with a max-age e.g. 1hour or something Commented May 18, 2023 at 13:16
  • @unusedspoon I agree, I would calculate an isPast boolean in a preprocess and utilize it within the node template. Concerning the caching you can get around that using the following answer as an example drupal.stackexchange.com/a/243788/20866 Commented May 18, 2023 at 19:01


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.