Hello, I am passing data from controller to template "index.html" to render them.
index.html file includes from sidebar.html, so index.html file is made up of sidebar.html too
The problem is that, if I try to access data inside sidebar.html, it is empty.
What is the solution?
评论:
tgaz:
ComfortablyNull:https://golang.org/pkg/text/template/:
{{template "name"}} The template with the specified name is executed with nil data. {{template "name" pipeline}} The template with the specified name is executed with dot set to the value of the pipeline.
You should be using the second form, and likely pass dot as the pipeline.
CrappyFap69:Are you using the template package?
If so you probably have to pass the data to the sidebar template with '.' :
Quick and dirty example:
package main import ( "html/template" "os" ) // Notice the '.' being passed after the template name. // This passes all the curently scoped data to the template const index = `{{ .hello }} {{template "sidebar" .}}` const sidebar = `{{ .bye }}` func main() { data := map[string]string{"hello": "hello", "bye": "goodbye!"} template.ParseFiles() sideBarTemplate, err := template.New("sidebar").Parse(sidebar) if err != nil { panic(err) } t, err := sideBarTemplate.New("index").Parse(index) if err != nil { panic(err) } t.Execute(os.Stdout, data) }
This should output:
hello goodbye!
LaughingCabbage_:It works like a charm!
<html> <body>{{ .class.member }}</body> </html>
