为了账号安全,请及时绑定邮箱和手机立即绑定

不替换占位符

不替换占位符

Go
绝地无双 2022-08-01 14:59:59
我正在试验这个包。我也已经管理了例如页眉,页脚,导航栏等包含在基本模板中:http/template{{ define "base" }}    <!DOCTYPE html>    <html>    <!-- 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 }}因此,此处的变量应替换为当前 URL。但是,这仅在网站上显示为空 ():CurrentURL""<small></small>但现在我想替换一个变量,它在网页上仅显示为“”。Go 代码: 解析器: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 -->我做错了什么?
查看完整描述

2 回答

?
www说

TA贡献1775条经验 获得超8个赞

您必须将上下文传递给实例化模板。用

{{ template "content" .}}

将数据传递到模板。.content


查看完整回答
反对 回复 2022-08-01
?
白衣非少年

TA贡献1155条经验 获得超0个赞

您不会将任何数据传递给子模板。根据文档:


{{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.


查看完整回答
反对 回复 2022-08-01
  • 2 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号