Score:0

Node template suggestion based on date field

ng flag

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

unusedspoon avatar
aq flag
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
cn flag
@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 https://drupal.stackexchange.com/a/243788/20866
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.