templates - Go:如何管理嵌套模板?

标签 templates go nested

试图以一种理智的方式使用模板,但我认为我的做法是错误的。

基本模板是

{{define "base"}}<!DOCTYPE html>
<html lang="en">
<head>
{{template "head" .}}
{{template "meta" . }}

</head>
<body>
<!-- some html -->
    {{template "body" .}}   
</body>

页面模板是

{{define "head"}}<title>{{.Title}}</title>{{end}}
{{define "body"}}<h2>{{.Title}}</h2>

<p>{{.Content}}</p>

{{end}}

我可以这样输出模板

package main

import (
    "database/sql"
    "github.com/gin-gonic/gin"
    "html/template"
)

func singleHandler(db *sql.DB, r *gin.Engine) gin.HandlerFunc {

    return gin.HandlerFunc(func(c *gin.Context) {

        html := template.Must(template.ParseFiles("templates/_base.tmpl", "templates/single.tmpl", "templates/meta.tmpl"))
        r.SetHTMLTemplate(html)

// get data from database

        data := struct {
            E *model.E
            M []model.M
        }{
            e,
            m,
        }

        c.Render(200, c.Engine.HTMLRender, "base", data)
    })
}

但这意味着如果我将来为其他内容 block 添加一些模板,我将不得不遍历所有其他文件并将新模板添加到 template.ParseFiles(...) 中。此外,我必须添加所有新代码以将该模板的数据填充到每个应该执行其他操作的模块中。

构建模块和嵌套模板的预期方式是什么?

最佳答案

我的解决方案:

在基本模板的开头添加注释行,如 "templates/_base.tmpl"、"templates/single.tmpl"、"templates/meta.tmpl"

读取模板文件字符串并将它们动态传递给template.ParseFiles()

关于templates - Go:如何管理嵌套模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31117988/

相关文章:

javascript - 我无法输出 Handlebars 模板中的数据

c++ - 作为模板类成员的模板类的特化

methods - 返回接收者本身(Go)的方法的目的是什么?

c++ - 数组元素的总和作为 constexpr

C++:从父类(super class)调用函数模板

超时 Goroutine 的 Golang 间歇性行为

json - 如何在 Go 中将 byte/uint8 数组编码为 json 数组?

python - 覆盖继承的默认支持对象(如 dict、list)的嵌套 JSON 编码

c# - 如何根据外部 GridView 选择填充内部 GridView (ASP.NET/C#)

amazon-web-services - 获取 Cloudformation 错误 : Embedded stack was not successfully created