猿问

如何在 Go 的 html/template 中获取地图元素的结构字段?

我有一个结构Task:


type Task struct {

   cmd string

   args []string

   desc string

}

我初始化了一个映射,它将上述Task结构作为值和 astring作为键(任务名称)


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/template仅使用上述内容来解析 html 页面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打印,但是当涉及到Task使用{{$value.desc}}它的领域时,它就行不通了。


在这种情况下,我怎样才能得到desc每个task?


慕运维8079593
浏览 161回答 1
1回答

慕沐林林

注意:您可以在Go Playground 中尝试/检查您的工作修改后的代码。如果您希望template包能够访问这些字段,则必须导出这些字段。您可以通过以大写字母开头来导出字段:type Task struct {&nbsp; &nbsp;cmd string&nbsp; &nbsp;args []string&nbsp; &nbsp;Desc string}请注意,我只Desc在此处更改,您必须将要在模板中引用的任何其他字段大写。导出后,Desc当然将所有引用更改为大写:var taskMap = map[string]Task{&nbsp; &nbsp; "find": Task{&nbsp; &nbsp; &nbsp; &nbsp; cmd: "find",&nbsp; &nbsp; &nbsp; &nbsp; args: []string{"/tmp/"},&nbsp; &nbsp; &nbsp; &nbsp; Desc: "find files in /tmp dir",&nbsp; &nbsp; },&nbsp; &nbsp; "grep": Task{&nbsp; &nbsp; &nbsp; &nbsp; cmd: "grep",&nbsp; &nbsp; &nbsp; &nbsp; args:[]string{"foo","/tmp/*", "-R"},&nbsp; &nbsp; &nbsp; &nbsp; Desc: "grep files match having foo",&nbsp; &nbsp; },}而且在模板中:<html>{{range $key, $value := .}}&nbsp; &nbsp;<li>Task Name:&nbsp; &nbsp; &nbsp; &nbsp; {{$key}}</li>&nbsp; &nbsp;<li>Task Value:&nbsp; &nbsp; &nbsp; &nbsp;{{$value}}</li>&nbsp; &nbsp;<li>Task description: {{$value.Desc}}</li>{{end}}</html>输出:<html><li>Task Name:&nbsp; &nbsp; &nbsp; &nbsp; find</li><li>Task Value:&nbsp; &nbsp; &nbsp; &nbsp;{find [/tmp/] find files in /tmp dir}</li><li>Task description: find files in /tmp dir</li><li>Task Name:&nbsp; &nbsp; &nbsp; &nbsp; grep</li><li>Task Value:&nbsp; &nbsp; &nbsp; &nbsp;{grep [foo /tmp/* -R] grep files match having foo}</li><li>Task description: grep files match having foo</li></html>
随时随地看视频慕课网APP

相关分类

Go
我要回答