栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

注意:您可以在 Go Playground中
尝试/签出您工作的修改后的代码。


如果希望

template
软件包能够访问字段,则必须导出字段。您可以通过以大写字母开头的字段来导出该字段:

type Task struct {   cmd string   args []string   Desc string}

请注意,我仅

Desc
在此处进行了更改,您必须将要在模板中引用的所有其他字段都大写。

导出之后

Desc
,请当然将所有引用更改为大写:

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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446414.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号