Skip to content Skip to sidebar Skip to footer

How To Show A Table From A Slice With My Struct

I want to show a table that each row contains my struct data. Here is my struct: type My_Struct struct { FIRST_FIELD string SECOND_FIELD string THIED_FIELD string

Solution 1:

It seems like you want the Go Template package.

Here's an example of how you may use it: Define a handler that passes an instance of a struct with some defined field(s) to a view that uses Go Templates:

type MyStruct struct {
        SomeField string
}

funcMyStructHandler(w http.ResponseWriter, r *http.Request) {
        ms := MyStruct{
                SomeField: "Hello Friends",
        }

        t := template.Must(template.ParseFiles("./showmystruct.html"))
t.Execute(w, ms)
}

Access the struct fields using the Go Template syntax in your view (showmystruct.html):

<!DOCTYPE html><title>Show My Struct</title><h1>{{ .SomeField }}</h1>

Update

If you are interested particularly in passing a list, and iterating over that, then the {{ range }} keyword is useful. Also, there's a pretty common pattern (at least in my world) where you pass a PageData{} struct to the view.

Here's an expanded example, adding a list of structs, and a PageData struct (so we can access its fields in the template):

type MyStruct struct {
    SomeField string
}

type PageData struct {
    Title string
    Data []MyStruct
}

funcMyStructHandler(w http.ResponseWriter, r *http.Request) {
        data := PageData{
            Title: "My Super Awesome Page of Structs",
            Data: []MyStruct{
                MyStruct{
                    SomeField: "Hello Friends",
                },
                MyStruct{
                    SomeField: "Goodbye Friends",
                },
            }

        t := template.Must(template.ParseFiles("./showmystruct.html"))
        t.Execute(w, data)

}

And the modified template (showmystruct.html):

<!DOCTYPE html><title>{{ .Title }}</title><ul>
  {{ range .Data }}
    <li>{{ .SomeField }}</li>
  {{ end }}
</ul>

Post a Comment for "How To Show A Table From A Slice With My Struct"