Navbar: Best way to test what current page is

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:

    <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>

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.

Maybe, this link would be helpful for you.

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 }}
{{ end }}

You can also active menu by compare the last URL element

{{ $lastUrlElement1 := index (last 1 (split (delimit (split .Permalink "/") "," "") ",")) 0 }}
 {{ $lastUrlElement2 := index (last 1 (split (delimit (split $currentURL "/") "," "") ",")) 0 }}
{{ if eq $lastUrlElement1 $lastUrlElement2 }}
  <div class="active"></div>
{{ end }}

You can set $currentURL outer scope of the range method

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!