【问题标题】:Variable not visible in partial变量在部分中不可见
【发布时间】:2015-04-18 12:50:48
【问题描述】:

为什么我的page 对象的title 属性没有填充到标题模板中?

这是我的小围棋程序

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)
}

这里是模板/post.html 文件:

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

还有我的模板/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

【问题讨论】:

标签: templates go


【解决方案1】:

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

改用{{template "header.html" .}}

有关详细信息,请参阅text/template 的操作部分。

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    相关资源
    最近更新 更多