有没有一种方法可以在Golang的HTML中显示一个具有值结构的map[key-string]字段?

huangapple go评论69阅读模式
英文:

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 (
	&quot;os&quot;
	&quot;text/template&quot;
)

type A struct {
	Timing string
}

func main() {
	inp := `
	&lt;html&gt;
	
	{{ range $key,$value:= .}}
		Key:{{$key}}, Timing {{$value.Timing}}
	{{end}}
	&lt;/html&gt;
`
	valueMap := map[string]A{
		&quot;key&quot;: A{
			Timing: &quot;1&quot;,
		},
	}
	t, err := template.New(&quot;test&quot;).Parse(inp)
	if err != nil {
		panic(err)
	}
	err = t.Execute(os.Stdout, valueMap)
	if err != nil {
		panic(err)
	}
}

huangapple
  • 本文由 发表于 2022年5月7日 02:14:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/72145790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定