I have a partial to render a navigation bar on my site and want to mark the currently seen page. I went for a simple solution as the Menu features didn’t seem so straight forward and I want something that’s flexible and easy to maintain.
I now arrived at this:
<nav>
<ul>
<li><a {{ if eq .Title "Home" }}class="active"{{ end }} href="/">Home</a></li>
<li><a {{ if eq .Title "Events" }}class="active"{{ end }} href="/events/">Events</a></li>
<li><a {{ if eq .Title "Projects" }}class="active"{{ end }} href="/projects/">Projects</a></li>
<li><a {{ if eq .Title "Gallery" }}class="active"{{ end }} href="/gallery/">Gallery</a></li>
<li><a {{ if eq .Title "Contact" }}class="active"{{ end }} href="/contact/">Contact</a></li>
</ul>
</nav>
This works well, but I was curious if someone sees a less repetitive approach. Given the brevity of it, I doubt tinkering with arrays is an improvement.
And I don’t get the point what’s the benefit hardcoded the menu.
The more general way is to make a menu.toml file in the config folder and use it something like this.
{{ range .Site.Menus.main }}
<a href="{{ .URL | relURL }}">
{{ safeHTML .Name }}
</a>
{{ end }}
You can also active menu by compare the last URL element
You’re right, it’s not such a good idea to hardcode the navigation in the template, and content and themes should be kept semantically separate where possible. I’ve moved the navigation into the global config and render the menu in a template similar to your example; definitely a step up now that I played around with it.
I’ll give your active menu example a try when I have properly set up child pages to test it. Thanks for the suggestions!