英文:
Is there a way to display a field of a map[key-string] with value-struct, in html, in golang?
问题
我有一个数据类型为map[key-string] value-struct的变量,并且我想要显示结构体中的一个字段(Timing)。
我尝试了各种变化一个小时,但似乎无法解决。如果有任何指导,将不胜感激!
对于格式问题,我表示抱歉,我是新手,请多包涵!
我的代码
英文:
I have a datatype of map[key-string] value-struct, and I'm trying to display a field(Timing) of the struct
I tried all sort of variations for an hour, can't seem to figure it out. Would appreciate any guidance on this, thank you!
Also apologies on the formatting, am new, do bear with me!
my code
答案1
得分: 1
使用{{$value.Timing}}代替内部循环。
// You can edit this code!
// Click here and start typing.
package main
import (
"os"
"text/template"
)
type A struct {
Timing string
}
func main() {
inp := `
<html>
{{ range $key,$value:= .}}
Key:{{$key}}, Timing {{$value.Timing}}
{{end}}
</html>
`
valueMap := map[string]A{
"key": A{
Timing: "1",
},
}
t, err := template.New("test").Parse(inp)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, valueMap)
if err != nil {
panic(err)
}
}
请注意,这是一个Go语言代码示例,用于在HTML模板中使用range
循环遍历valueMap
中的键值对,并输出每个键和对应的Timing
值。
英文:
Instead of inner loop, use {{$value.Timing}}.
// You can edit this code!
// Click here and start typing.
package main
import (
"os"
"text/template"
)
type A struct {
Timing string
}
func main() {
inp := `
<html>
{{ range $key,$value:= .}}
Key:{{$key}}, Timing {{$value.Timing}}
{{end}}
</html>
`
valueMap := map[string]A{
"key": A{
Timing: "1",
},
}
t, err := template.New("test").Parse(inp)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, valueMap)
if err != nil {
panic(err)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论