简体   繁体   中英

With Golang Templates how can I set a variable in each template?

How can I set a variable in each template that I can use in other templates eg

{{ set title "Title" }}

in one template then in my layout

<title> {{ title }} </title>

Then when it's rendered

tmpl, _ := template.ParseFiles("layout.html", "home.html")

it will set the title according to whatever was set in home.html instead of having to make a struct for each view page when it isn't really necessary. I hope I made sense, thanks.

Just for clarification:

layout.html:
<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }} </title>
  </head>
  <body>

  </body>
</html>

home.html:
{{ set Title "Home" . }}
<h1> {{ Title }} Page </h1>

If you want to use the Value in another template you can pipeline it to the dot:

{{with $title := "SomeTitle"}}
{{$title}} <--prints the value on the page
{{template "body" .}}
{{end}}

body template:

{{define "body"}}
<h1>{{.}}</h1> <--prints "SomeTitle" again
{{end}}

As far as i know it is not possible to go upwards in the chain. So layout.html gets rendered before home.html , so you cant pass a value back.

In your example it would be the best solution to use a struct and pass it from the layout.html to the home.html using the dot :

main.go

package main

import (
    "html/template"
    "net/http"
)

type WebData struct {
    Title string
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    tmpl, _ := template.ParseFiles("layout.html", "home.html")
    wd := WebData{
        Title: "Home",
    }
    tmpl.Execute(w, &wd)
}

func pageHandler(w http.ResponseWriter, r *http.Request) {
    tmpl, _ := template.ParseFiles("layout.html", "page.html")
    wd := WebData{
        Title: "Page",
    }
    tmpl.Execute(w, &wd)
}

func main() {
    http.HandleFunc("/home", homeHandler)
    http.HandleFunc("/page", pageHandler)
    http.ListenAndServe(":8080", nil)
}

layout.html

<!DOCTYPE html>
<html>
  <head>
    <title>{{.Title}} </title>
  </head>
  <body>
    {{template "body" .}}
  </body>
</html>

home.html

{{define "body"}}
<h1>home.html {{.Title}}</h1>
{{end}}

page.html

{{define "body"}}
<h1>page.html {{.Title}}</h1>
{{end}}

Also go has a nice documentation on how to use templates:

http://golang.org/pkg/text/template/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM