<p>Hello, I am passing data from controller to template "index.html" to render them.</p>
<p>index.html file includes from sidebar.html, so index.html file is made up of sidebar.html too</p>
<p>The problem is that, if I try to access data inside sidebar.html, it is empty.</p>
<p>What is the solution?</p>
<hr/>**评论:**<br/><br/>tgaz: <pre><p><a href="https://golang.org/pkg/text/template/:" rel="nofollow">https://golang.org/pkg/text/template/:</a></p>
<pre><code>{{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.
</code></pre>
<p>You should be using the second form, and likely pass dot as the pipeline.</p></pre>ComfortablyNull: <pre><p>Are you using the <a href="https://golang.org/pkg/html/template/" rel="nofollow">template</a> package? </p>
<p>If so you probably have to pass the data to the sidebar template with '.' :</p>
<p>Quick and dirty example:</p>
<pre><code>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)
}
</code></pre>
<p>This should output:</p>
<blockquote>
<p>hello goodbye!</p>
</blockquote></pre>CrappyFap69: <pre><p>It works like a charm!</p></pre>LaughingCabbage_: <pre><p><code>
<html>
<body>{{ .class.member }}</body>
</html>
</code></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传