render html templates in gin (go)

May 1, 2019 ยท View on GitHub

GoDoc

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.

Benifits

  1. You don't have to add and parse files in each handler
  2. Supports debug mode. This allows you to visualize the change you did by simply refreshing the page without restarting the server.
  3. Simple rendering syntax for the template
// suppose `templates/articles/list.html` is your file to be rendered
c.HTML(http.StatusOK, "articles/list", "")
  1. More structured templates directory where you can place entities in logical units.
  2. Configure layout file
  3. Configure template file extension
  4. Configure templates directory
  5. Feels friendlier for people coming from communities like rails, express or django.
  6. All of this without loosing any performance of gin!

Usage

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

Note

  1. Error is thrown if either of the layout file or templates directory doesn't exist
  2. Only one extension can be configured
  3. Only one layout fine can be used

Todo

  • Provide options to customize
    • template dir
    • layout
    • template extensions
    • includes dir
    • add template helpers
  • Add string and glob option back
  • Tests

Further steps...

I would like to know the thoughts of the community about this.

And based on that we have the following options I guess:

  1. Make this part of contrib's multitemplate
  2. Add this as another contrib module, say multitemplate_extras
  3. Leave the above, I will make another repo :)