I have a content type Event that has a startdate (field_eventdate) and an optional enddate (field_eventend). Although it's optional, the enddate is often filled in by the users with the same date as the startdate. So I want to hide the enddate if it's equal to the startdate or display it on the same line as the startdate when it's different.
e.g.
2020-02-02 10:00
Here comes more text for a single day event
and
2020-02-02 10:00 - 2020-02-03 16:00
Here is more text for a multiday event
So far I managed to delete the enddate from the render array when it's equal:
function mytheme_preprocess_node__event(&$variables) {
$startdate = $variables['content']['field_eventdate'][0]['#markup'];
$enddate = $variables['content']['field_eventend'][0]['#markup'];
if ($startdate === $enddate) {
unset($variables['content']['field_eventend']);
}
else {
// add an &em-dash; so the dates are nicely spaced
$variables['content']['field_eventend'][0]['#markup'] = " — " . $enddate;
// add float-left to the start date so they end up on the same line
// TODO: what goes here?
}
}
But I cannot find out how to notice in a twig template that I have a startdate and an enddate and therefore add 'float' css classes to put them in line.
I have tried to add a special attribute to the 'field_eventdate' field, and add a 'float-left' class in the twig template for the field, but the custom attribute gets lost somewhere.
How can I solve this problem?
field--field-eventdate.html.twig
but I cannot find if field_eventend exists. I prefer to fall back to the default templates as much as possible, so I don't want to create anode--event.html.twig
if possible. Can I set a custom attribute on the field_eventdate in the preprocess function? If so, how?