golang 中的渲染模板

Rendering template in golang

我正在使用 Go 中的 echo 框架来创建一个网络应用程序。我有一个名为 templates 的目录,其中有两个目录 layoutsusers。目录树如下:

layouts
|--------default.tmpl
|--------footer.tmpl
|--------header.tmpl
|--------sidebar.tmpl

users
|--------index.tmpl

页眉、页脚和侧边栏的代码类似于:

{{define "header"}}
<!-- some html here -->
{{ end }} 
....

default.tmpl如下:

{{ define "default" }}
{{ template "header" }}

{{ template "sidebar" }}

<div class="content-wrapper">
    <div class="container-fluid">

        <div class="row">
            <div class="col-md-12">
                <h2 class="page-title">Dashboard</h2>
                {{ template "content" .}}
            </div>
        </div>
    </div>
</div>

{{ template "footer" }}
{{ end }}

users\index.tmpl

{{define "index"}}
    {{template "default"}}
{{end}}

{{define "content"}}
<p>Hello world</p>
{{end}}

现在,我使用

解析文件
t := &Template{}
t.templates = template.Must(template.ParseGlob("views/layouts/*"))
t.templates = template.Must(template.ParseGlob("views/user/*"))

并尝试渲染它

func User(c echo.Context) error {
    return c.Render(http.StatusOK, "index", nil)
}

但我只收到内部服务器错误。我也不知道如何调试模板。如果 users\index.tmpl 中不包含其他模板标签,则代码有效。但是当我尝试在其中包含主模板时,出现错误 returns。我在这里做错了什么?

设法解决了这个问题。此页面 https://elithrar.github.io/article/approximating-html-template-inheritance/ 有帮助。 基本上,我必须将解析模板的代码更改为:

tpls, err := filepath.Glob("views/user/*")
if err != nil {
    log.Fatal(err)
}

layouts, err := filepath.Glob("views/layouts/*")
if err != nil {
    log.Fatal(err)
}

for _, layout := range layouts {
    files := append(layouts, tpls)
    t.templates = template.Must(template.ParseFiles(files...))
}