
在 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 }}⚠️ 注意事项:
- {{ template "name" }}(无参数)等价于 {{ template "name" nil }},子模板失去所有数据;
- 若需传入特定字段(如仅传标题),可写 {{ template "head" .Title }},但此时 head.tpl 中需用 {{ . }} 访问(而非 {{ .Title }});
- 多层嵌套时(如 head 再 include meta),每层 template 都需明确传递所需上下文;
- 使用 template 时,确保目标模板已通过 define 正确定义且被 ParseGlob 或 ParseFiles 加载。
该机制保障了模板作用域的清晰与安全——既避免隐式依赖,也防止意外泄露敏感数据。









