【问题标题】:Rendering template in golanggolang 中的渲染模板
【发布时间】:2016-04-19 06:48:51
【问题描述】:

我正在使用 Go 中的 echo 框架来创建一个 Web 应用程序。我有一个名为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 中不包含其他模板标签,则该代码有效。但是当我尝试在其中包含主模板时,错误返回。我在这里做错了什么?

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    设法解决了这个问题。此页面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...))
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      相关资源
      最近更新 更多