Jonathan Wilson
Jonathan Wilson

Reputation: 11

How to access a struct slice element key directly in a template file

I am loading some template files and attempting to compile them with some structs I've defined.

The following example is working. I'd like to know if there is a better way of formatting my templateFile to directly access config.Servers[1].Ip1 without needing two sets of {{}}

templateFile: {{$a := index .Servers 1 }}{{$a.Ip1}} some extra text

learn.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)
    }

}

Upvotes: 1

Views: 241

Answers (1)

Adi
Adi

Reputation: 387

Please refer this: https://golang.org/pkg/html/template/

You have to use {{}} in your HTML template, if you wish to access any Struct variable.

Upvotes: 1

Related Questions