Menu with unlimited levels

I discover new ways to exploit Go Template every day… I know a lot of people may already be doing it, but for some who aren’t here it is:

{{/* layouts/partials/main_nav.html */}}
<div class="main-nav">
	{{ with .Site.Menus.main }}
	<ul>
		{{ range . }}
			{{ template "main_nav_item" . }}
		{{ end }}
	</ul>
	{{ end }}
</div>

{{ define "main_nav_item" }}
<li>
	<a href="{{ .URL }}">{{ .Name }}</a>
	{{ if .HasChildren }}
		<ul>
			{{ range .Children }}
				{{ template "main_nav_item" . }}
			{{ end }}
		</ul>
	{{ end }}
</li>
{{ end }}

The code above defines a template block containing a menu item which includes itself. This allows to infinitely repeat this block of HTML thus creating an infinite number of navigation level.

The usage of a template block defined in the same template file saves us here the creation a partial file which in this context would be used solely by the layouts/partials/main-navigation.html template file.

11 Likes

I have (something very similar to) this in action here for the curious :smiley:

1 Like

It would be very useful if some description of what the code is doing were provided. If not in line commenting, possibly some mention of why it is special enough to be considered a tip. Not everyone can read the code like a book. :slightly_smiling_face:

You’re right! I’ll take time today to edit that “spur of the moment” thread into something more useful for everyone.

Also, remember that template names are global. Very generic ones will eventually bite your ass.

1 Like

Alright, updated the initial post to better explain what is happening and emphasize the unique name of the template block.

Cheers.