加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

使用Golang模板,如何在每个模板中设置变量?

发布时间:2020-12-16 09:29:51 所属栏目:大数据 来源:网络整理
导读:如何在每个模板中设置一个我可以在其他模板中使用的变量,例如 {{set title“Title”}} 在一个模板然后在我的布局中 标题 {{title}} / title 然后当它被渲染 tmpl,_:= template.ParseFiles(“layout.html”,“home.html”) 它将根据home.html中设置的内容设
如何在每个模板中设置一个我可以在其他模板中使用的变量,例如

{{set title“Title”}}

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

<标题> {{title}}< / title>

然后当它被渲染

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

它将根据home.html中设置的内容设置标题,而不是在没有必要时为每个视图页面创建结构.我希望我有道理,谢谢.

只是为了澄清:

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

  </body>
</html>

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

解决方法

如果要在另一个模板中使用Value,可以将其传递给点:

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

身体模板:

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

据我所知,链条上不可能向上.
所以layout.html在home.html之前呈现,所以你不能传回一个值.

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

main.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,"page.html")
    wd := WebData{
        Title: "Page",&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/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读