Gin is a very good library, with a great performance! I was trying it out and learned that a lot of people were struggling with templating (as I did myself). gin-contrib's multitemplate is pretty good. But I think it lacks small things like debug mode, support for structured template rendering. Of-course, multitemplate should not be dictating how to structure your templates. But I think it makes sense to support a standard layout structure in a contrib package.
So I modified the multitemplate a bit, may be this can be called as multitemplate-extras
? (tried to highlight some benefits).
The goal is to make html template rendering in gin simple and straight forward without having to write much code.
- You don't have to add and parse files in each handler
- Supports debug mode. This allows you to visualize the change you did by simply refreshing the page without restarting the server.
- Simple rendering syntax for the template
// suppose `templates/articles/list.html` is your file to be rendered
c.HTML(http.StatusOK, "articles/list", "")
- More structured templates directory where you can place entities in logical units.
- Configure layout file
- Configure template file extension
- Configure templates directory
- Feels friendlier for people coming from communities like rails, express or django.
- All of this without loosing any performance of gin!
router := gin.Default()
// Set html render options
htmlRender := GinHTMLRender.New()
htmlRender.Debug = gin.IsDebugging()
htmlRender.Layout = "layouts/default"
// htmlRender.TemplatesDir = "templates/" // default
// htmlRender.Ext = ".html" // default
// Tell gin to use our html render
router.HTMLRender = htmlRender.Create()
Suppose your structure is
|-- templates/
|--
|-- 400.html
|-- 404.html
|-- layouts/
|--- default.html
|-- articles/
|--- list.html
|--- form.html
And if you want to render templates/articles/list.html
in your handler
c.HTML(http.StatusOK, "articles/list", "")
See it in action here, here and here and a full demo with the source
- Error is thrown if either of the layout file or templates directory doesn't exist
- Only one extension can be configured
- Only one layout fine can be used
- Provide options to customize
template dirlayouttemplate extensions- includes dir
- add template helpers
- Add string and glob option back
- Tests
I would like to know the thoughts of the community about this.
And based on that we have the following options I guess:
- Make this part of contrib's
multitemplate
- Add this as another contrib module, say
multitemplate_extras
- Leave the above, I will make another repo :)
Thank you, you save my life.