Farhad Kocharli
Farhad Kocharli

Reputation: 61

Access specific field in struct which is in slice Golang templates

I have such where I send to template years data (which is slice of structs). How can I access on template side AcaYear field of only 2nd item (struct)? Whole second item I can access as {{index . 1 }}. I also can range over slice and get AcaYear fields of both all items. But need only AcaYear field of second item (result should be 2021-2022).

package main

import (
    "log"
    "os"
    "text/template"
)

type course struct {
    Number string
    Name   string
    Units  string
}

type semester struct {
    Term    string
    Courses []course
}

type year struct {
    AcaYear string
    Fall    semester
    Spring  semester
    Summer  semester
}

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseFiles("tpl.gohtml"))
}

func main() {
    years := []year{
        year{
            AcaYear: "2020-2021",
            Fall: semester{
                Term: "Fall",
                Courses: []course{
                    course{"CSCI-40", "Introduction to Programming in Go", "4"},
                    course{"CSCI-130", "Introduction to Web Programming with Go", "4"},
                    course{"CSCI-140", "Mobile Apps Using Go", "4"},
                },
            },
            Spring: semester{
                Term: "Spring",
                Courses: []course{
                    course{"CSCI-50", "Advanced Go", "5"},
                    course{"CSCI-190", "Advanced Web Programming with Go", "5"},
                    course{"CSCI-191", "Advanced Mobile Apps With Go", "5"},
                },
            },
        },
        year{
            AcaYear: "2021-2022",
            Fall: semester{
                Term: "Fall",
                Courses: []course{
                    course{"CSCI-40", "Introduction to Programming in Go", "4"},
                    course{"CSCI-130", "Introduction to Web Programming with Go", "4"},
                    course{"CSCI-140", "Mobile Apps Using Go", "4"},
                },
            },
            Spring: semester{
                Term: "Spring",
                Courses: []course{
                    course{"CSCI-50", "Advanced Go", "5"},
                    course{"CSCI-190", "Advanced Web Programming with Go", "5"},
                    course{"CSCI-191", "Advanced Mobile Apps With Go", "5"},
                },
            },
        },
    }

    err := tpl.Execute(os.Stdout, years)
    if err != nil {
        log.Fatalln(err)
    }
}

Upvotes: 2

Views: 761

Answers (1)

icza
icza

Reputation: 417472

Simply group the index call and apply the .AcaYear field selector on the result:

{{ (index . 1).AcaYear }}

This will output (try it on the Go Playground):

2021-2022

Upvotes: 1

Related Questions