Active Links in Hugo
Here’s a way to create an active links in Hugo. By that I mean that link can be targetted for a different style if it points to the page currently viewed. Typically this is done by adding class="active"
.
The way I prefer is to set href="#"
. This can be targetted using a CSS attribute selector
a[href="#"] { color: red }
<ul class="latest">
{{ $currentPage := . }}
{{ range first 20 (where .Site.RegularPages "Section" "posts") }}
<li>
{{ if eq $currentPage . }}
<a href="#">{{ .Title }}</a></li>
{{ else }}
<a href="{{ .Permalink }}">{{ .Title }}</a>
{{ end }}
</li>
{{ end }}
</ul>
How it works
As Hugo does its work page by page it comes across the first line {{ $currentPage := . }}
. The dot is the page it’s on so it stores that page in the variable.
Next as it iterates through the pages with the range function gets to the page that is the same as that stored in {{ $currentPage := . }}
it uses the first option in the 'if
statement.