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?
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.
@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
Most helpful comment
Well theres no documentation but you can do it like this:
main.tmpl:
whatever.tmpl:
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.