Khrisna Gunanasurya
Khrisna Gunanasurya

Reputation: 745

How to get this value in html files golang

In HTML file, I want to get the ID and the Username, but how to do that? because what I got always a blank page.

// DataHandler struct
type DataHandler struct {
    SessionDataHandler session.SessionData
}

// HomeHandler function
func HomeHandler(w http.ResponseWriter, r *http.Request) {
    sessionData := session.GetSession(w, r)
    data := DataHandler{
        SessionDataHandler: session.SessionData{
            ID:       sessionData.ID,
            Username: sessionData.Username,
        },
    }

    tmp, err := template.ParseFiles(
        "web/index.html",
        "web/template/header.html",
        "web/template/footer.html",
    )
    if err != nil {
        log.Fatal(err)
    }

    err = tmp.Execute(w, data)
    if err != nil {
        log.Println(err)
    }
}

I already tried using these in the HTML but still no luck.

{{ .SessionDataHandler }}
{{ .SessionDataHandler.ID }}
{{ .SessionDataHandler.session.ID }}
{{ .SessionDataHandler.sessionData.ID }}
{{ .SessionDataHandler.session.sessionData.ID }}

how to call them?

Edited:

// SessionData struct
type SessionData struct {
    ID       int
    Username string
}

Edited again: (HTML files)

{{ template "header.html" . }}
{{ .SessionDataHandler.ID }}
  <!-- HOME PRO-->
  <div class="home-pro"> 

    <!-- PRO BANNER HEAD -->
    <div class="banr-head">
      <div class="container">
        <div class="row"> 

Upvotes: 0

Views: 1032

Answers (1)

negi Yogi
negi Yogi

Reputation: 2278

// package main  
package main

    import (
        "fmt"
        "os"
        "html/template"
    )

    type SessionData struct {
        ID int
        Username string
    }

    type dataHandler struct {
        SessionDataHandler SessionData
    }

    var data = dataHandler{
        SessionDataHandler: SessionData{
            ID:       123,       // This
            Username: "Joe", // and This
        },
    }

    var tmpl = `
    {{ .SessionDataHandler.ID }}
    `

    type dataHandler2 struct {
        SessionDataHandler SessionData
    }

    var data2 = dataHandler2{
        SessionDataHandler: SessionData{
            ID:       123,       // This
            Username: "Joe", // and This
        },
    }

    var tmpl2 = `
    {{ .SessionDataHandler.ID }}
    {{ .SessionDataHandler.Username }}
    `

    func main() {
        t, err := template.New("tmpl").Parse(tmpl)
        if err != nil {
            panic(err)
        }
        fmt.Println(t.Execute(os.Stdout, data))

        t2, err := template.New("tmpl").Parse(tmpl2)
        if err != nil {
            panic(err)
        }
        fmt.Println(t2.Execute(os.Stdout, data2))
    }

This should be the correct one.

Upvotes: 2

Related Questions