在Go模板中使用地图。

huangapple go评论70阅读模式
英文:

Use maps in Go templates

问题

我需要在模板中使用一个地图,但是语法不正确。

                <tr>
                    <td>印度</td>
                    <td>{{$val.Agent.Imei}}</td>
                    <td>{{$val.Jid}}</td>
                    <td>{{.LoginTimeMap[$val.Jid]}}
                </tr>

它说{{.LoginTimeMap[$val.Jid]}}中的[]是意外的坏字符U+005B '[' in command。

请帮忙解决。

英文:

I need to use a map in template, however, the syntax is not correct

                &lt;tr&gt;
						&lt;td&gt;India&lt;/td&gt;
						&lt;td&gt;{{$val.Agent.Imei}}&lt;/td&gt;
						&lt;td&gt;{{$val.Jid}}&lt;/td&gt;
						&lt;td&gt;{{.LoginTimeMap[$val.Jid]}}
					&lt;/tr&gt;

it saids the [] in {{.LoginTimeMap[$val.Jid]}} is unexpected bad character U+005B '[' in command

Please Help

答案1

得分: 5

在模板中,使用index代替[]

函数文档

>index
>
> 返回将第一个参数按照后续参数进行索引的结果。因此,在Go语法中,"index x 1 2 3"等价于x[1][2][3]。每个被索引的项必须是一个map、slice或array。

Playground

英文:

In templates, use index instead of [].

http://golang.org/pkg/text/template/#hdr-Functions

>index
>
> Returns the result of indexing its first argument by the
> following arguments. Thus "index x 1 2 3" is, in Go syntax,
> x[1][2][3]. Each indexed item must be a map, slice, or array.

Playground.

huangapple
  • 本文由 发表于 2014年9月23日 18:08:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/25992370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定