go - With Golang Templates how can I set a variable in each template? -
how can set variable in each template can use in other templates e.g.
{{ set title "title" }}
in 1 template in layout
<title> {{ title }} </title>
then when it's rendered
tmpl, _ := template.parsefiles("layout.html", "home.html")
it set title according whatever set in home.html
instead of having make struct
each view page when isn't necessary. hope made sense, thanks.
just clarification:
layout.html: <!doctype html> <html> <head> <title>{{ title }} </title> </head> <body> </body> </html> home.html: {{ set title "home" . }} <h1> {{ title }} page </h1>
if want use value in template can pipeline dot:
{{with $title := "sometitle"}} {{$title}} <--prints value on page {{template "body" .}} {{end}}
body template:
{{define "body"}} <h1>{{.}}</h1> <--prints "sometitle" again {{end}}
as far know not possible go upwards in chain. layout.html
gets rendered before home.html
, cant pass value back.
in example best solution use struct , pass layout.html
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}}
also go has nice documentation on how use templates:
Comments
Post a Comment