Placeholders are not replaced

断了今生、忘了曾经 提交于 2021-02-05 10:49:50

问题


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

{{ define "content" }}
    [...]
                    <h1 class="text-light text-right">404</h1>
                    <small>{{.CurrentURL}}</small>
    [...]
{{ end }}

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

Go Code: Parser:

func (parser *TemplateParser) ParseTemplate(name string) (tpl *template.Template, err error) {
  root, err := template.New("root").Parse(rootTmpl)
  // ...
  return root.ParseFiles(files...)
}

Route:

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

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

What am I doing wrong?


回答1:


You have to pass the context to the instantiated templates. Use

{{ template "content" .}}

to pass the data in . to the content template.




回答2:


You're not passing any data to the child templates. 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.


来源:https://stackoverflow.com/questions/65582487/placeholders-are-not-replaced

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!