戈朗 : Ordering map by slice in Go templates

标签 go go-templates

我有一个关于如何在 Go 模板中按 slice 排序 map 以及是否可行的问题。

问题:我有一段有序的变量名称,我想在网站上显示,伴随它们我有一个变量信息的元数据映射,我想与变量一起显示。

如果我将以下结构传递给模板:

type Data struct {
       Variables    []string
       Information  map[string]int
}

我会遍历 slice 并将变量名传递给 map

{{ range $v := .Variables }} {{ index .Information $v }} {{ end }} // Doesn't work.

这是带有示例的 Go Playground。 https://play.golang.org/p/AL2csnXdoU

问题:我该怎么做?

我对 Golang 还很陌生。感谢任何输入。

最佳答案

以下应该有效。要访问 range 内的 .Information,您应该使用 $,这在您的 Playground 示例中基本上是 d

{{ range .Variables }} {{ index $.Information . }} {{ end }}

关于戈朗 : Ordering map by slice in Go templates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37089103/

相关文章:

ruby - 如何覆盖 String.scan 和 FindAllString 中的匹配行为?

templates - 防止模板中转义正斜杠

go - 模板和自定义函数;错误 : executing "templName" at <"funcName"> is not a define function

go - 将数组的索引传递给模板

casting - 类型断言/类型切换是否性能不佳/在 Go 中很慢?

string - 如何在go中有效地连接字符串

firebase - Golang Firebase管理员SDK

database - 无法获取更新查询的数据库响应以在 go 中进一步执行

go - 在 Hugo 部分模板中,如何访问辅助/附加参数?

如果不匹配,Golang 模板将忽略