如何解决占位符不会被替换
我正在试用 http/template
包。
我也已经做到了,例如页眉、页脚、导航栏等都包含在基本模板中:
{{ define "base" }}
<!DOCTYPE html>
<html lang="en">
<!-- Start Head -->
<head>
{{ template "head" }}
</head>
<!-- End Head -->
<!-- Start Body -->
<body>
{{ template "navbar" }}
{{ template "content" }}
{{ template "footer" }}
</body>
<!-- End Body -->
</html>
{{ end }}
404 页面:
{{ define "content" }}
[...]
<h1 class="text-light text-right">404</h1>
<small>{{.CurrentURL}}</small>
[...]
{{ end }}
因此此处变量 CurrentURL
应替换为当前 URL。
但是,这仅在网站上显示为空 (""
):
<small></small>
去代码: 解析器:
func (parser *TemplateParser) ParseTemplate(name string) (tpl *template.Template,err error) {
root,err := template.New("root").Parse(roottmpl)
// ...
return root.ParseFiles(files...)
}
路线:
func (ws *WebServer) Exec(name string,r *http.Request,w http.ResponseWriter,data map[string]interface{}) (err error) {
// ...
// add default data
data["CurrentURL"] = r.URL.RequestURI()
// ...
return tpl.Execute(w,data)
}
即使使用数组,我也不能使用 range
等:
type Test struct {
CurrentURL string
C []string
}
t := Test{
CurrentURL: "Current URL",C: []string {"C1","c2","ccc4"},}
tpl.Execute(w,t)
<ul>
{{range .C}}
<li>{{.}}</li>
{{end}}
</ul>
<!-- No <li></li> is created -->
我做错了什么?
解决方法
您必须将上下文传递给实例化的模板。使用
{{ template "content" .}}
将 .
中的数据传递给 content
模板。
您没有将任何数据传递给子模板。 Per the docs:
{{template "name"}}
The template with the specified name is executed with nil data.
{{template "name" pipeline}}
The template with the specified name is executed with dot set
to the value of the pipeline.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。