Web 应用程序的 Golang 模板

我正在用 GoLang 编写一个 Web 应用程序,而不使用任何框架。


例如,我正在尝试创建layout类似于 nodejs 中的布局。


=== layout.html ====


 {{ define "layout"}}

 <!DOCTYPE html>

 <html>

  <head>

  <meta charset='utf-8'>

    <link href="/static/style.css" rel="stylesheet" media="all" type="text/css">

   </head>

   <body>

     {{ template "content"}}

   </body>

</html>


{{ end }}

然后我在 home.html 中有一些内容


{{ define "content"}}

    <h1>{{.Title}}</h1>

    <div>This is a test</div>

{{ end }}

这种方法有两个问题


(1)我的Execute模板代码,似乎没有将数据传递给内容


templates.ExecuteTemplate(w, "layout", &Page{Title: "Home", Body: nil})

(2) 如果我想拥有多个具有相同布局的页面,上述方法将不起作用,因为它没有指定要加载的内容。


有人可以解释在 GoLang 中使用 tempates 和“布局”的策略吗?


MM们
浏览 117回答 2
2回答

烙印99

(1)我的Execute模板代码,似乎没有将数据传递给内容正如人们在评论中指出的那样,您需要使用数据显式调用模板:{{ template "content" . }}注意零件后面的点"content"。(2) 如果我想拥有多个具有相同布局的页面,上述方法将不起作用,因为它没有指定要加载的内容。有几种方法可以解决这个问题。我要做的就是这个。我不在{{ define "content" }}每个模板中。相反,我将所有模板解析为一个:tmpls, err := template.ParseGlob(tmplGlob)然后对于每个请求,我克隆布局并将所需的模板设置为"content":func executeTemplate(tmpls *template.Template, tmplName string, w io.Writer, data interface{}) error {&nbsp; &nbsp; var err error&nbsp; &nbsp; layout := tmpls.Lookup("layout.html")&nbsp; &nbsp; if layout == nil {&nbsp; &nbsp; &nbsp; &nbsp; return errNoLayout&nbsp; &nbsp; }&nbsp; &nbsp; layout, err = layout.Clone()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; t := tmpls.Lookup(tmplName)&nbsp; &nbsp; if t == nil {&nbsp; &nbsp; &nbsp; &nbsp; return errNoTemplate&nbsp; &nbsp; }&nbsp; &nbsp; _, err = layout.AddParseTree("content", t.Tree)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; return layout.Execute(w, data)}

智慧大石

(2) 如果我想拥有多个具有相同布局的页面,上述方法将不起作用,因为它没有指定要加载的内容。你需要为此建立一些东西。它可以是一个模板 func,它知道模板,接收块名称和参数以调用 t.executeTemplate,就像你做的那样。但是这种方法有一个严重的缺点,因为它要求每个请求都生成自己的编译模板。它可以是视图参数的方法。它可以让你构建一次模板,为每个请求重新使用这个实例,只有参数会改变。无论如何,如果您继续使用内置template帮助器,它就不能是变量,它被锁定为仅使用静态字符串。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go