Golang模板变量FooterField在footer模板中无法正常解析问题
问题原因
Go标准库html/template调用子模板时不会默认传递当前上下文数据,必须显式指定传入参数:
- 你在index.html中调用header模板时使用
{{template "header" . }},末尾的.代表将当前的Data结构体实例传递给header子模板,因此header可以正常读取到所有字段值 - 但调用footer模板时使用的是
{{template "footer"}},没有传入任何参数,footer模板的作用域内没有对应的数据对象,因此.FooterField取值为空。
修复方案
修改index.html中调用footer模板的代码,补充传入当前上下文参数即可:
{{define "index"}}{{template "header" . }} <h1>Index template</h1> <div>{{.FooterField}}</div> {{template "footer" . }}{{end}}
修改后footer模板就能正常读取到FooterField的值。
内容的提问来源于stack exchange,提问作者pigfox
相关产品推荐
相关产品推荐

