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

How to set a variable in each template that I can use in other templates, for example.

{{ set title "Title" }}

in one template, then in my layout

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

Then when it is displayed

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

it will set the header according to what was set in home.html , instead of having to make a struct for each page of the view when it’s not really needed. Hope I make sense, thanks.

For clarification only:

 layout.html: <!DOCTYPE html> <html> <head> <title>{{ title }} </title> </head> <body> </body> </html> home.html: {{ set Title "Home" . }} <h1> {{ Title }} Page </h1> 
+6
source share
1 answer

If you want to use the value in another template, you can associate it with a dot:

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

body pattern:

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

As far as I know, it is impossible to move up the chain. This way layout.html is output before home.html , so you cannot pass the value back.

In your example, it would be a better solution to use a structure and pass it from layout.html to home.html using 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}} 

You also have some good documentation on how to use templates:

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

+7
source

Source: https://habr.com/ru/post/988423/


All Articles