【问题标题】:Placeholders are not replaced占位符不被替换
【发布时间】:2021-01-05 16:10:13
【问题描述】:

我正在试验包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>

但是现在我想替换一个变量,该变量在网页上只显示为“”。

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

我做错了什么?

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

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

    {{ template "content" .}}
    

    . 中的数据传递给content 模板。

    【讨论】:

    • 哦,这么小的一个点,我正在寻找自己的愚蠢。感谢您的回答!
    【解决方案2】:

    您没有将任何数据传递给子模板。 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.
    

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 1970-01-01
      • 2013-04-08
      • 2017-09-11
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2018-07-27
      相关资源
      最近更新 更多