Go HTML templates: defining array of array of strings to range over

前提是你 提交于 2020-01-06 06:24:13

问题


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?

来源:https://stackoverflow.com/questions/55913146/go-html-templates-defining-array-of-array-of-strings-to-range-over

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!