gpt4 book ai didi

templates - 部分变量不可见

转载 作者:IT王子 更新时间:2023-10-29 02:34:07 24 4
gpt4 key购买 nike

为什么我的 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)
}

这里是 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

最佳答案

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

试试 {{template "header.html".}}

请参阅 text/template 的操作部分了解详情。

关于templates - 部分变量不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29717586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com