Gin: Documentation for using layout files with templates?

Created on 13 Feb 2015  路  4Comments  路  Source: gin-gonic/gin

Most templating (moustache, erb, etc) libraries usually include a way to have a layout template:

<html>
    <head></head>
    <body>
        {{ content }}
    </body>
</html>

And subpages get injected into the content/yield part of the layout.

Is there documentation or a standard way to use a layout file?

question

Most helpful comment

Well theres no documentation but you can do it like this:

var baseTemplate = "main.tmpl"

r.GET("/", func(c *gin.Context) {
    r.SetHTMLTemplate(template.Must(template.ParseFiles(baseTemplate, "whatever.tmpl")))
    c.HTML(200, "base", data)
})

main.tmpl:

{{define "base"}}
<html>
    <head></head>
    <body>
        {{template "content" .}}
    </body>
</html>
{{end}}

whatever.tmpl:

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

Because it relies on Engine and not Context, it needs to either be directly in the handler or you need to make *Engine a global.

All 4 comments

Well theres no documentation but you can do it like this:

var baseTemplate = "main.tmpl"

r.GET("/", func(c *gin.Context) {
    r.SetHTMLTemplate(template.Must(template.ParseFiles(baseTemplate, "whatever.tmpl")))
    c.HTML(200, "base", data)
})

main.tmpl:

{{define "base"}}
<html>
    <head></head>
    <body>
        {{template "content" .}}
    </body>
</html>
{{end}}

whatever.tmpl:

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

Because it relies on Engine and not Context, it needs to either be directly in the handler or you need to make *Engine a global.

I just did this package. hope it's help.

https://github.com/michelloworld/ez-gin-template

@michelloworld LGTM, added to https://github.com/gin-gonic/contrib/blob/master/README.md, thanks.

Well theres no documentation but you can do it like this:

var baseTemplate = "main.tmpl"

r.GET("/", func(c *gin.Context) {
    r.SetHTMLTemplate(template.Must(template.ParseFiles(baseTemplate, "whatever.tmpl")))
    c.HTML(200, "base", data)
})

main.tmpl:

{{define "base"}}
<html>
    <head></head>
    <body>
        {{template "content" .}}
    </body>
</html>
{{end}}

whatever.tmpl:

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

Because it relies on Engine and not Context, it needs to either be directly in the handler or you need to make *Engine a global.

Is this unsafe?

[GIN] 2019/08/06 - 05:47:33 | 200 |      315.85碌s |  xxx.xxx.xxx.xx | GET      /dashboard
[GIN-debug] [WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called
at initialization. ie. before any route is registered or the router is listening in a socket:

        router := gin.Default()
        router.SetHTMLTemplate(template) // << good place
Was this page helpful?
0 / 5 - 0 ratings

Related issues

wangcn picture wangcn  路  3Comments

kekemuyu picture kekemuyu  路  3Comments

mastrolinux picture mastrolinux  路  3Comments

cxk280 picture cxk280  路  3Comments

frederikhors picture frederikhors  路  3Comments