0

In Jinja2 (Python Flask) templates, I'm able to create a static navigation menu by defining a list of tuples with code similar to the following:

{% for item in [('', 'Home'), ('menu1', 'Menu1'), ('menu2', 'Menu2')] %}
<li><a href="{% if item[0] == '' %}/{% else %}{{ '/%s/' % item[0] }}{% endif %}">{{ item[1] }}</a></li>
{%- endfor %}

I'd like to create something similar in Go HTML templates. I assume the equivalent to a list of tuples would be an array/slice of arrays of strings, i.e., something like

{{ $items := { {"", "Home"}, {"menu1", "Menu1"}, {"menu2", "Menu2"} } }}
{{ range $items }}
<li><a href="{{if .[0] == \"\"}}/{{else}}{{ \"/.[0]/\" }}{{end}}">{{ .[1] }}</a></li>
{{end}}

However, at runtime, specifically when Go tries to parse the template files it panics with unexpected "{" in command (it used to panic with unexpected "{" in range when I used a range directly).

So, is it possible to declare an array of arrays of strings in a template?

Joe Abbate
  • 1,692
  • 1
  • 13
  • 19
  • 1
    i don't think golang template support it, you can define the array in Go code – zzn Apr 30 '19 at 04:36
  • 2
    Nothing out of the box that supports something like that in Go's stdlib `html/template` package, however you can define your own template functions that will help you with that. For example: https://play.golang.com/p/FXapl76qngy – mkopriva Apr 30 '19 at 07:18
  • Thanks, @mkopriva. That's certainly useful. – Joe Abbate Apr 30 '19 at 12:32
  • FWIW, I ended up defining the menu items as a slice of structs in the Go code (as suggested by zzn) which gets passed with other page data to `template.ExecuteTemplate`. The template code then uses a `{{range .NavMenu}}` where the arg is that slice. I hadn't shown it before but the `
  • ` also had to identify one of the items as currently active, and that wasn't as easy as in Jinja, requiring a variable declaration outside the range, because range apparently only has access to the individual elements, not the data visible before the range.
  • – Joe Abbate Jun 28 '19 at 21:38