When i start using Gin i struggling with template system. I find out many people have the same problem.
I have found some code in Github (multitemplate.go, gin_html_render.go) which help but not everything i need is supported like Template helpers.
Check it out my package in official gin contribute repository: gin-gonic/contrib
- Simple rendering syntax for the template
// suppose "app/views/articles/list.html" is your file to be rendered
c.HTML(http.StatusOK, "articles/list", "")
- Configure layout file
- Configure template file extension
- Configure templates directory
- Feels friendlier for people coming from communities like rails, express or django.
- Template Helpers (gin_html_render.go is not support yet)
Supports rails style partials, simply name any template with underscore starting. So If you have "dashboard/index.tmpl" add "dashboard/_header.tmpl". Also there is a shared partial directory called "partials" under your template directory, anything you put there will be included with all templates.
dashboard/_header.tmpl - define the template name
{{define "header"}}
<h1>Hi, This is Header</h1>
{{ end }}
dashboard/index.tmpl - call partial template by it's name
{{define "content"}}
Bla Bla Bla...
{{template "header" .}}
{{ end }}
Suppose your structure is
|-- app/views/
|-- layouts/
|--- base.html
|-- blogs/
|--- index.html
|--- show.html
See in "example" folder
go get https://github.com/michelloworld/ez-gin-template
import eztemplate "github.com/michelloworld/ez-gin-template"
r := gin.Default()
render := eztemplate.New()
// render.TemplatesDir = "app/views/" // default
// render.Layout = "layouts/base" // default
// render.Ext = ".html" // default
// render.Debug = false // default
// render.TemplateFuncMap = template.FuncMap{}
r.HTMLRender = render.Init()
r.Run(":9000")
I hope this package will resolve your problem about template system. and give you an idea about how to use template helpers in Gin framework
Thanks, multitemplate.go, gin_html_render.go for the idea