doujia7779 2015-04-18 12:50
浏览 23
已采纳

变量在部分中不可见

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

here is my small go program

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

here is the templates/post.html file:

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

and my templates/header.html file:

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

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

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

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条回答 默认 最新

  • dongxiong1941 2015-04-18 13:19
    关注

    The {{template "header.html"}} form doesn't pass any data.

    Try {{template "header.html" .}} instead.

    See the Actions section of text/template for details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?