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

标签 templates go

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

以下示例正在运行。我想知道是否有更好的方法来格式化我的 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/

相关文章:

c++ - 什么时候删除模板实例比删除非模板重载更可取?

c++ - 将 operator== 重载为带有模板参数的自由函数的语法是什么?

go - 输入正确但在 golang 中输出 panic

GoREST 端点路径

c++ - 模板类中的静态成员初始化

C++ 简单模板递归

php - 使用 vprintf 的廉价 php 模板?

go - 为什么传入/tmp/go-build644681611/command-line-arguments/_obj/exe去运行

go - 如何转换 unicode(例如 :\u2713) code to a rune(ex: ✓) in golang?

json - Golang facebook api huandu/facebook 帖子描述问题