Home > Software design >  Template variable not resolving everywhere
Template variable not resolving everywhere

Time:11-07

I am building a website using Golang templates and needed to display some text in the footer template. It's a variable that resolves in header.html and index.html.

package main

import (
    "fmt"
    "html/template"
    "log"
    "net/http"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

type Data struct {
    Title string
    Field1 string
    Field2 template.HTML
    FooterField string
}

var tmpl *template.Template

func main() {
    router := mux.NewRouter()

    port := ":8085"
    data := Data{}
    data.Title = "Title"
    data.FooterField = "This text does not appear in the footer template"

    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        err := tmpl.ExecuteTemplate(w, "index", data)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    })

    var err error
    tmpl, err = template.ParseGlob("views/*")
    if err != nil {
        panic(err.Error())
    }

    router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
    })

    fmt.Println("Server running on localhost"   port)

    err = http.ListenAndServe(port, handlers.CompressHandler(router))
    if err != nil {
        log.Fatal(err)
    }
}

And in the ./views I have header.html

{{define "header"}}<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{{.Title}}</title></head><body><h1>Header template</h1><div>{{.FooterField}}</div>{{end}}

index.html

{{define "index"}}{{template "header" . }}
<h1>Index template</h1>
<div>{{.FooterField}}</div>
{{template "footer"}}{{end}}

footer.html

{{define "footer"}}<h1>Footer template</h1>
Missing FooterField->{{.FooterField}}</body></html>{{end}}

And finally the output in the browser on http://localhost:8085/

Header template
This text does not appear in the footer template
Index template
This text does not appear in the footer template
Footer template
Missing FooterField->

This code should be able to be reproduced simply by copying and pasting.

Any clue to what my issue is?

CodePudding user response:

you are not passing anything to the footer template. But you pass . to the header template, so you see the value of .FooterField only there.

In index.html change it to: {{template "footer" . }}

  • Related