go - 将一个模板渲染到另一个模板中,而无需每次都解析它们

标签 go

我有三个这样的模板:

基础.html:

<h1>Base.html rendered here</h1>
{{template "content" .}}

view.html:

{{define "content"}}
...
{{end}}

编辑.html:

{{define "content"}}
...
{{end}}

我将它们存储在"template"文件夹中。

我想要的是动态更改将在 {{template "content".}} 位置呈现的模板,而不是每次都解析。所以我不想要的是:

func main() {
   http.HandleFunc("/edit", handlerEdit)
   http.HandleFunc("/view", handlerView)
   http.ListenAndServe(":8080", nil)
}
func handlerView(w http.ResponseWriter, req *http.Request) {
   renderTemplate(w, req, "view")
}

func handlerEdit(w http.ResponseWriter, req *http.Request) {
   renderTemplate(w, req, "edit")
}

func renderTemplate(w http.ResponseWriter, req *http.Request, tmpl    string) {
   templates, err := template.ParseFiles("templates/base.html",  "templates/"+tmpl+".html")
   if err != nil {
       fmt.Println("Something goes wrong ", err)
       return
   }
   someData := &Page{Title: "QWE", Body: []byte("sample body")}
   templates.Execute(w, someData)
}

我正在查看 template.ParseGlobe(),以便做这样的事情

var templates = template.Must(template.ParseGlob("templates/*.html"))
... //and then somthing like this:
err := templates.ExecuteTemplate(w, tmpl+".html", p)

但是 ExecuteTamplate() 只接收一个字符串作为模板名称。在这种情况下,我如何渲染两个或更多模板?

最佳答案

不是在调用 ExecuteTemplate 时直接写入 http.ResponseWriter,而是写入一个字节缓冲区,并通过准备调用将其发送到下一个模板使用 template.HTML 调用。

var b bytes.Buffer

var templates = template.Must(template.ParseGlob("templates/*.html"))

err := templates.ExecuteTemplate(b, templ_1, p)
if err != nil { //handle err }
err := templates.ExecuteTemplate(w, templ_2, template.HTML(b.String()))
if err != nil { //handle err }

如果您打算使用未知数量的模板,您可以使用字符串捕获中间步骤:

var strtmp string
err := templates.ExecuteTemplate(b, templ_1, p)
if err != nil { //handle err }

strtemp = b.String()  //store the output
b.Reset()             //prep buffer for next template's output

err := templates.ExecuteTemplate(b, templ_2, template.HTML(strtmp))
if err != nil { //handle err }

//... until all templates are applied

b.WriteTo(w)  //Send the final output to the ResponseWriter

编辑:正如@Zhuharev 所指出的,如果 View 和编辑模板的组成是固定的,那么它们都可以引用 base 而不是试图提供对 View 或编辑的引用的 base:

{{define "viewContent"}}
{{template "templates/base.html" .}}
...Current view.html template...
{{end}}

{{define "editContent"}}
{{template "templates/base.html" .}}
...Current edit.html template...
{{end}}

关于go - 将一个模板渲染到另一个模板中,而无需每次都解析它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32503247/

相关文章:

go - 如何为带有动态变量的where子句编写gorm函数

go - 使用不同级别的接口(interface)

sql - PostgreSQL 插入多个表和行

go - 在 golang 中写一个字符串的两个部分

go - 如何永久删除 GORM 中的关联

http 服务器正在运行,但在与计时器一起使用时收到 404

pointers - 将结构作为参数传递给函数进行修改的内存/处理器效率最高的方法是什么?

docker - 它说 “connection reset”不能使Docker容器在本地主机上运行?

Go 和 Redisgo : DialURL error: NOAUTH Authentication required

mongodb - 如何获取原始 M 内的值