

新闻资讯
技术教程在 go 的 `html/template` 中,使用 `{{ template "name" }}` 包含子模板时,默认不会自动继承当前作用域的数据;必须显式传入上下文(如 `.`)才能使变量在子模板中可用。
当你在 index.tpl 中写 {{ template "head" }},Go 模板引擎会以 空结构体(nil 上下文) 渲染 "head" 模板——这意味着 {{ .Title }} 在 head.tpl 中求值为 "",导致
✅ 正确做法是:显式将当前数据上下文(即 .)作为第二个参数传给 template 动作:
{{ template "head" . }}修改后的 index.tpl 片段如下:
{{ define "index" }}
{{ template "head" . }}
Main info:
Title: {{ .Title }}
Desc: {{ .Desc }}
{{ end }}这样,head.tpl 就能正常访问 .Title 和其他字段:
{{ define "head" }}
{{ .Title }}
{{ end }}⚠️ 注意事项:
该机制保障了模板作用域的清晰与安全——既避免隐式依赖,也防止意外泄露敏感数据。