Go的html/template中结构体字段必须首字母大写才能访问,如{{.Name}};嵌套字段需逐级导出;安全渲染用{{.Content|safeHTML}}或template.HTML;模板继承靠{{define}}+{{template}},需先解析base再子模板;Execute前须设Content-Type头,避免response已提交。
Go 的 html/template 默认禁止直接访问未导出字段(即小写开头的字段),传入结构体后如果字段为空或报错,大概率是字段没导出。
type User struct { Name string },不能写成 name string
{{.Name}} 访问,{{.}} 表示当前作用域对象本身User.Profile.AvatarURL,则 Profile 和 AvatarURL 都得大写开头json:"avatar_url" template:"avatar" 不生效,html/template 不识别这类 tag,只能靠字段名本身html/template 默认会对 {{.Content}} 做 HTML 转义,防止 XSS。但有时你明确知道内容可信
(比如后台生成的 Markdown 渲染结果),需要原样输出——这时不能用 {{.Content}},而要用 {{.Content|safeHTML}}。
template.HTML 类型的值才被视作“已消毒”,例如:data := map[string]interface{}{"Raw": template.HTML("Hello")}strings.Replace 或正则“手动去转义”,那会破坏模板的安全机制),应先用专用库(如 microcosm-cc/bluemonday)白名单过滤,再转成 template.HTML
{{.UserInput | html}} —— html 是默认 filter,加了反而多转义一次Go 模板没有原生 layout 概念,靠 {{define}} + {{template}} 模拟继承,但容易因执行顺序或作用域出错。
base.html)里用 {{define "content"}}{{end}} 占位,子模板用 {{define "content"}}...{{end}} 覆盖{{template "content"}} 找不到定义;推荐用 template.ParseGlob("templates/*.html") 一次性加载全部{{.}} 是传入的 data,不是 base 模板的 data;若需在 base 中访问数据,把 data 显式传给 {{template "header" .}}
{{define}} 内部重复定义同名区块,Go 模板会静默覆盖,不易调试常见错误是忘记设置响应头或提前写了 body,导致 http.ResponseWriter 已被提交(committed),再调用 Execute 就 panic:http: multiple response.WriteHeader calls 或 write on closed body。
Execute 前调用 w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write 或 fmt.Fprint(w, ...),否则响应流已开启Execute 前加判断:if !w.Header().Get("Content-Type") { w.Header().Set("Content-Type", "text/html; charset=utf-8") }renderTemplate(w http.ResponseWriter, name string, data interface{}) 函数,统一处理 header 和 errorfmt.Printf 看执行路径。