Halvor William Sanden
All articles

Hugo timestamp with relURL

I’m fairly new to Hugo, but I’ve worked with my fair share of template languages to feel reasonably at home. Enough to both see familiar patterns, but also wonder "why have they done it like that?" Although the documentation could be a lot better, my biggest gripe now is the patchy support of syntax highlighting and formatting.

When my team tried to combine a timestamp with a relative url we got an example of how things can get a bit messy.

The solution

<link 
	rel="stylesheet" 
	type="text/css" 
	href="{{ "css/main.min.css?ts=" | relURL }}{{ now.Unix }}"
/>

Some spacing, double quotes and brackets that can trip you up, but completely understandable and fairly logical. And it makes sense in the bigger picture of how the template language works.

An alternative to timestamp is fingerprinting.

First try

The reason for struggling with this perhaps more than necessary was that we first implemented the timestamp only:

<link
	rel="stylesheet"
	type="text/css"
	href="css/main.min.css?ts={{ now.Unix }}"
/>

But when we later tried the following to implement the relative url, it only rendered the timestamp code as a string.

<link
	rel="stylesheet"
	type="text/css"
	href="{{ "css/main.min.css?ts={{ now.Unix }}" | relURL }}"
/>

What I would guess

<link
	rel="stylesheet"
	type="text/css"
	href="{{ envBase }}css/main.min.css?ts={{ time.changed.Epoch }}"
/>

{{ envBase }} would be the root of the current environment, and {{ time.changed.Epoch }} would be when the file was last generated or changed. It’s a bit cleaner and more straightforward for me, familiar with Twig.

Gained knowledge

UX/UI

Programming

Tools and productivity