如何在Go的html/template中获取地图元素的struct字段? [英] How can I get the struct field of a map elem in Go's html/template?
问题描述
我有一个结构Task
:
type Task struct {
cmd string
args []string
desc string
}
然后我将上面的Task
结构作为值并将string
作为键(任务名称)的映射初始化为
And I init a map which take the above Task
struct as a value and a string
as a key(the task name)
var taskMap = map[string]Task{
"find": Task{
cmd: "find",
args: []string{"/tmp/"},
desc: "find files in /tmp dir",
},
"grep": Task{
cmd: "grep",
args:[]string{"foo","/tmp/*", "-R"},
desc: "grep files match having foo",
},
}
,而我想仅使用上述taskMap
来使用html/template
解析html页面.
and I want to parse a html page using html/template
just using the above taskMap
.
func listHandle(w http.ResponseWriter, r *http.Request){
t, _ := template.ParseFiles("index.tmpl")
t.Execute(w, taskMap)
}
这是index.tmpl
:
<html>
{{range $key, $value := .}}
<li>Task Name: {{$key}}</li>
<li>Task Value: {{$value}}</li>
<li>Task description: {{$value.desc}}</li>
{{end}}
</html>
我可以成功打印出$key
和value
,但是当使用{{$value.desc}}
进入Task
字段时,将无法正常工作.
I can get the $key
and value
printed successfully, but When It comes to the field of Task
using {{$value.desc}}
it wont work.
在这种情况下,如何获取每个task
的desc
?
How can I get the desc
of each task
in this case?
推荐答案
注意:您可以在 去游乐场 .
Note: you can try/check out your working modified code in the Go Playground.
如果希望template
包能够访问字段,则必须导出字段.您可以通过以大写字母开头的字段来导出该字段:
If you want the template
package to be able to access the fields, you have to export the fields. You can export a field by starting it with an uppercase letter:
type Task struct {
cmd string
args []string
Desc string
}
请注意,我仅在此处更改了Desc
,您必须将要在模板中引用的所有其他字段都大写.
Note that I only changed Desc
here, you have to uppercase any other fields you want to refer to in the template.
导出后,请当然将所有引用更改为大写Desc
:
After this exporting, change all references to uppercase Desc
of course:
var taskMap = map[string]Task{
"find": Task{
cmd: "find",
args: []string{"/tmp/"},
Desc: "find files in /tmp dir",
},
"grep": Task{
cmd: "grep",
args:[]string{"foo","/tmp/*", "-R"},
Desc: "grep files match having foo",
},
}
以及在模板中:
<html>
{{range $key, $value := .}}
<li>Task Name: {{$key}}</li>
<li>Task Value: {{$value}}</li>
<li>Task description: {{$value.Desc}}</li>
{{end}}
</html>
输出:
<html>
<li>Task Name: find</li>
<li>Task Value: {find [/tmp/] find files in /tmp dir}</li>
<li>Task description: find files in /tmp dir</li>
<li>Task Name: grep</li>
<li>Task Value: {grep [foo /tmp/* -R] grep files match having foo}</li>
<li>Task description: grep files match having foo</li>
</html>
这篇关于如何在Go的html/template中获取地图元素的struct字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!