占位符不被替换
时间:2023-04-27
浏览:129
作者:佚名
有志者,事竟成!如果你在学习Golang,那么本文《占位符不被替换》,就很适合你!文章讲解的知识点主要包括golang,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
我正在试验这个包http/template。
我还已经管理了例如页眉、页脚、导航栏等包含在基本模板中:
{{ define "base" }}
{{ template "head" }}
{{ template "navbar" }}
{{ template "content" }}
{{ template "footer" }}
{{ end }}
404页面:
{{ define "content" }}
[...]
404
{{.CurrentURL}}
[...]
{{ end }}
所以这里的变量CurrentURL应该替换为当前的 URL。但是,这仅""在网站上显示为空 ( ):
但是现在我想替换一个变量,该变量在网页上仅显示为“”。
围棋代码:解析器:
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)
-
{{range .C}}
- {{.}} {{end}}
我究竟做错了什么?
正确答案
您必须将上下文传递给实例化的模板。采用
{{ template "content" .}}
将数据传递.给content模板。
到这里,我们也就讲完了《占位符不被替换》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于golang的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.28
热门专题
