【问题标题】:With Golang Templates how can I set a variable in each template?使用 Golang 模板如何在每个模板中设置一个变量?
【发布时间】:2015-08-17 00:53:01
【问题描述】:

如何在每个模板中设置一个可以在其他模板中使用的变量,例如

{{ set title "Title" }}

在一个模板中,然后在我的布局中

<title> {{ title }} </title>

然后当它被渲染时

tmpl, _ := template.ParseFiles("layout.html", "home.html")

它将根据home.html 中设置的任何内容设置标题,而不是在不需要时为每个视图页面创建struct。我希望我说得通,谢谢。

只是为了澄清:

layout.html:
<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }} </title>
  </head>
  <body>

  </body>
</html>

home.html:
{{ set Title "Home" . }}
<h1> {{ Title }} Page </h1>

【问题讨论】:

    标签: templates go


    【解决方案1】:

    如果您想在另一个模板中使用该值,您可以将其通过管道传递到点:

    {{with $title := "SomeTitle"}}
    {{$title}} <--prints the value on the page
    {{template "body" .}}
    {{end}}
    

    正文模板:

    {{define "body"}}
    <h1>{{.}}</h1> <--prints "SomeTitle" again
    {{end}}
    

    据我所知,不可能在链条中向上走。 所以layout.htmlhome.html 之前被渲染,所以你不能传回一个值。

    在您的示例中,最好的解决方案是使用结构并使用dot 将其从layout.html 传递到home.html

    ma​​in.go

    package main
    
    import (
        "html/template"
        "net/http"
    )
    
    type WebData struct {
        Title string
    }
    
    func homeHandler(w http.ResponseWriter, r *http.Request) {
        tmpl, _ := template.ParseFiles("layout.html", "home.html")
        wd := WebData{
            Title: "Home",
        }
        tmpl.Execute(w, &wd)
    }
    
    func pageHandler(w http.ResponseWriter, r *http.Request) {
        tmpl, _ := template.ParseFiles("layout.html", "page.html")
        wd := WebData{
            Title: "Page",
        }
        tmpl.Execute(w, &wd)
    }
    
    func main() {
        http.HandleFunc("/home", homeHandler)
        http.HandleFunc("/page", pageHandler)
        http.ListenAndServe(":8080", nil)
    }
    

    layout.html

    <!DOCTYPE html>
    <html>
      <head>
        <title>{{.Title}} </title>
      </head>
      <body>
        {{template "body" .}}
      </body>
    </html>
    

    home.html

    {{define "body"}}
    <h1>home.html {{.Title}}</h1>
    {{end}}
    

    page.html

    {{define "body"}}
    <h1>page.html {{.Title}}</h1>
    {{end}}
    

    还有一个很好的关于如何使用模板的文档:

    http://golang.org/pkg/text/template/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 2014-04-02
      • 2013-04-16
      • 1970-01-01
      • 2018-01-30
      相关资源
      最近更新 更多