Hi.
I have a page that displays a list of events. These are displayed differently depending on whether they are in the past or in the future.
The template (see below) seems to work ok in itself but the issue is that the time status of events is fixed at the time of deployment (Netlify). In other words, if I deploy on Monday, the event on Tuesday appears as a future event. It still appears as a future event on Wednesday, even though it is now in the past. If I redeploy the site, the problem is resolved but I’m hoping there’s a way to overcome the need to do this manually?
Here’s the relevant part of the template:
You’re using a static site generator. Therefore, your HTML pages are generated once and then delivered. If you create your pages on Monday, Tuesday is in the future. If someone looks at your pages on Tuesday, it’s the current day. Obviously.
The only way to overcome that if you want to stick with Hugo is to use JavaScript: Generate all events and have JavaScript display only those that are in the future.
You still have to regenerate your pages at certain moments because you’ll have to add new future events. Depending on the number of events, Hugo alone might not be the best tool – perhaps combining it with a database and generating parts of the pages dynamically (i.e. at view time) is a better solution.
Thanks for the super quick response, that makes perfect sense.
** Added for folks who might be also considering this…
The date formats provided by Hugo tokens don’t seem to be readily recognizable as valid dates by JS. one way to get around that is:
HTML Template:
// Get the current date
let currentDate = new Date();
// Get an array of all event dates
let eventDates = document.getElementsByClassName("event-date");
// For each event date in the list:
// Convert the Hugo date to a JS-readable format
// Convert to a Date object
// Check if past or future and add the appropriate class to the parent element in each case
for (date of eventDates) {
let validDate = date.textContent.slice(0, 10);
validDate = new Date(validDate);
if (validDate < currentDate) {
date.parentElement.classList.add("past")
} else {
date.parentElement.classList.add("future")
}
}```
Hat tip to [this related post](https://ar.al/2018/06/17/formatting-an-iso-8601-date-stamp-in-hugo/)