Go模板如何使用动态键访问Map数据?
本文介绍如何在Go模板中利用动态键访问Map数据。 一个常见场景是:根据切片中的键值,循环访问Map中对应的值。
假设我们有键值切片keylist和Mapdatamap:
keylist := []string{ "2021-02", "2020-08", "2020-07", "2020-05", "2020-02", "2020-01", } datamap := map[string]int{ "2021-02": 123, "2020-08": 234, "2020-07": 234234, "2020-05": 23423, "2020-02": 345345345, "2020-01": 456456, }
我们需要在模板中迭代keylist,并使用每个元素作为键,从datamap获取值。 直接使用{{.datamap.$date}}是错误的,Go模板引擎不支持这种动态键值访问。
正确的做法是使用Go模板引擎的index函数。 index函数可根据索引或键值从数组或Map中获取元素。 因此,模板代码应如下:
{{range $date := .keylist}} {{ $value := index $.datamap $date }} {{if $value}} <p>{{ $date }}: {{ $value }}</p> {{end}} {{end}}
这段代码通过{{range $date := .keylist}}循环遍历keylist。 每次循环中,index $.datamap $date使用$date作为键,从$.datamap (即datamap) 获取值,赋值给$value。 {{if $value}}判断值是否存在,避免错误。最后输出键值对。
需要注意的是,.datalist.$date这种写法在Go模板中无效。 index函数是解决此问题的关键。 示例中使用了index $.datamap $date,假设datamap直接包含所需数据。如果datamap的结构更复杂,则需要根据其结构调整代码以提取所需信息。