占位符未替换 [英] Placeholders are not replaced
问题描述
我正在尝试使用包 http/template
.
我也已经做到了例如页眉,页脚,导航栏等都包含在基本模板中:
I am experimenting with the package http/template
.
I have also already managed that e.g. the header, footer, navbar and so on were included in the base 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.但是,这只会在网站上显示为空("
):
So here the variable CurrentURL
should be replaced by the current URL.
However, this is only displayed empty (""
) on the website:
<small></small>
但是现在我要替换一个变量,该变量在网页上仅显示为".
But now I want to replace a variable, which is displayed on the web page only as "".
执行代码:解析器:
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
等:
Even with an array, I can't use range
etc:
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 -->
我在做什么错了?
推荐答案
您必须将上下文传递给实例化的模板.使用
You have to pass the context to the instantiated templates. Use
{{ template "content" .}}
会将.
中的数据传递到 content
模板.
to pass the data in .
to the content
template.
这篇关于占位符未替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!