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.