Hugo Variable Help -- too verbose? [Solved]

Hello,

I am new to templating with Hugo and would love some input.
I wrote this logic here to display page names in a nav, adding a ‘strong’ tag to the active page, and changing index name to “Home” for users. Was there a cleaner way to go about this? * I know the titleInRange is unnecessary - that was just for me to remember scope. I mean was there a way to avoid the nested ‘if’?

Also can someone help me with getting the “Home” nav link to show up first? It has a weight of zero, but it appears last. Also anyone have advice for complex whole page templating? Just practice?


{{ $title := .Title }}
{{ range .Site.Pages.ByWeight }}
  {{ $titleInRange := .Title }}
  {{ if eq $titleInRange .Site.Title }}

    {{ $titleInRange := "Home" }}
    {{ if eq .Title $title }}
      <a href="{{ .URL }}"><strong>{{ $titleInRange }}</strong></a>
    {{ else }}
      <a href="{{ .URL }}">{{ $titleInRange }}</a>
    {{ end }}
  {{ else }}  
    {{ if eq .Title $title }}
      <a href="{{ .URL }}"><strong>{{ $titleInRange }}</strong></a>
    {{ else }}
     <a href="{{ .URL }}">{{ $titleInRange }}</a>
    {{ end }}

  {{ end }}
{{ end }}

Instead of {{ if eq $titleInRange .Site.Title }} you can use .isHome: https://gohugo.io/variables/page/#page-variables

If you want to give a title to your index, you can create an _index.md besides index.html and add frontmatter to it like title or anything else, I am not sure how it can replace the value of .Title.

Thanks for the response. I created the _index.md in the content directory & it worked great.

Hi, i think you may be trying to build a menu, for which hugo has a dedicated system that will give you access to the IsMenuCurrent function in the menu templates to check whether the menu entry is your current page or not.

Moreover, if i’m reading correctly, your first if is only used to change the value of $titleInRange. So maybe you could reduce your code by using the cond function:

{{ $titleInRange := cond .IsHome "Home" .Title }}

So now you’re down to just one if. Hope that helps :slight_smile:

You don’t need to store the parent page’s title in a variable, it will always be available in the $ from within range or with so:

{{ if eq .Title $.Title }}

Also, you should checkout .Scratch, using it I was able to come up with the following.
You should try and improve it. Have fun discovering Hugo!

{{ range .Site.Pages.ByWeight }}
  {{ .Scratch.Set "title" (cond .IsHome "Home" .Title) }}
  {{ if or (and .IsHome $.IsHome) (eq .Title $.Title) }}
    {{ .Scratch.Set "title" (printf "<strong>%s</strong>" (.Scratch.Get "title") ) }}
  {{ end }}
  <a href="{{ .URL }}">{{ .Scratch.Get "title" | safeHTML}}</a>
{{ end }}

Thanks everyone. I am marking this as resolved.