gpt4 book ai didi

templates - 如何直接在模板文件中访问结构 slice 元素键

转载 作者:IT王子 更新时间:2023-10-29 02:10:02 24 4
gpt4 key购买 nike

我正在加载一些模板文件并尝试使用我定义的一些结构来编译它们。

以下示例正在运行。我想知道是否有更好的方法来格式化我的 templateFile 以直接访问 config.Servers[1].Ip1 而无需两套 { {}}

模板文件: {{$a := index .Servers 1 }}{{$a.Ip1}} 一些额外的文字

学习.go:

package main

import (
"html/template"
"os"
)

type Server struct {
Ip1 string
Ip2 string
}

type Configuration struct {
Servers []Server
}

func main() {
someServers := []Server{
{
Ip1: "1.1.1.1",
Ip2: "2.2.2.2",
},
{
Ip1: "3.3.3.3",
Ip2: "4.4.4.4",
},
}
config := Configuration{
Servers: someServers,
}

tmpl, err := template.ParseFiles("./templateFile")
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, config)
if err != nil {
panic(err)
}

}

最佳答案

请引用: https://golang.org/pkg/html/template/

如果您希望访问任何 Struct 变量,则必须在 HTML 模板中使用 {{}}。

关于templates - 如何直接在模板文件中访问结构 slice 元素键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49583751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com