在部分中,变量不可见。

huangapple go评论80阅读模式
英文:

Variable not visible in partial

问题

为什么我的page对象的title属性在头部模板中没有填充?

这是我的一个小型Go程序:

package main

import (
  "html/template"
  "os"
)

type Page struct {
  Title string
  Body  string
}

func main() {
  f, _ := os.Create("index.html")
  defer f.Close()

  page := Page{"I'm the title", "And I'm the body"}

  t := template.New("post.html")
  t = template.Must(t.ParseGlob("templates/*html"))
  t.Execute(f, page)
}

这是templates/post.html文件的内容:

{{template "header.html"}}
<article>
  {{.Body}}
</article>
{{template "footer.html"}}

这是templates/header.html文件的内容:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{{.Title}}</title>
  </head>
  <body>

为了完整起见,这是templates/footer.html文件的内容:

<footer>
&copy; 2015
</footer>
</body>
</html>

模板templates/post.html中的.Body变量被填充了,但是模板templates/header.html中的.Title为空,我认为这是因为它是从另一个模板渲染的局部模板...

如何使其工作?

我将完整的示例发布在gist上。

英文:

Why is the title attribute of my page object not populated in the header template ?

here is my small go program

package main
 
import (
  &quot;html/template&quot;
  &quot;os&quot;
)
 
type Page struct {
  Title string
  Body  string
}
 
func main() {
  f, _ := os.Create(&quot;index.html&quot;)
  defer f.Close()
 
  page := Page{&quot;I&#39;m the title&quot;, &quot;And I&#39;m the body&quot;}
 
  t := template.New(&quot;post.html&quot;)
  t = template.Must(t.ParseGlob(&quot;templates/*html&quot;))
  t.Execute(f, page)
}

here is the templates/post.html file:

{{template &quot;header.html&quot;}}
&lt;article&gt;
  {{.Body}}
&lt;/article&gt;
{{template &quot;footer.html&quot;}}

and my templates/header.html file:

&lt;!doctype html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;title&gt;{{.Title}}&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;

for the sake of completeness, my footer, templates/footer.html file:

&lt;footer&gt;
&amp;copy; 2015
&lt;/footer&gt;
&lt;/body&gt;
&lt;/html&gt;

The .Body variable in the templates/post.html template is filled, but the .Title in the templates/header.html template is empty, I think it's because it's a partial, rendered from another template...

How to make this work ?

I posted the complete above example as a gist

答案1

得分: 5

{{template "header.html"}} 表单没有传递任何数据。

尝试使用 {{template "header.html" .}} 替代。

有关详细信息,请参阅 text/template 的“Actions”部分。

英文:

The {{template &quot;header.html&quot;}} form doesn't pass any data.

Try {{template &quot;header.html&quot; .}} instead.

See the Actions section of text/template for details.

huangapple
  • 本文由 发表于 2015年4月18日 20:50:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/29717586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定