Load Go Template Includes from a Database Using Gorm

A powerful part of any template language is to load snippets that can be reused across your site.

This website is powered by a custom build CMS using templates loaded from a database, and I’ve just added a new feature called “includes” where you can load snippets from the database, inject data to that template and output it into your parent template.

This tutorial requires the following:

The way I have this set up, is in my func main() block, I have the following snippet:

    priFuncs = template.FuncMap{
        "LoadInclude": func(id int64, data interface{}) (ret template.HTML, err error) {
            var buf bytes.Buffer
            var src string
            err = db.DB().QueryRow("SELECT code FROM includes WHERE id = ?", id).Scan(&src)

            if err != nil {
                src = "Template not found"
            key := fmt.Sprintf("template-id-%v", id)
            t, err := template.New(key).Parse(src)
            t.Execute(&buf, data)
            ret = template.HTML(buf.String())

This is relying on a global priFuncs variable, you can set as:

var (
    priFuncs template.FuncMap

Then, when you are setting up your template variable, before you run a Parse function, place the following: .Funcs(priFuncs), so for example, this:


would be:


If you are using Martini and the Martini render library, you need to set it up a bit differently.

In your func main() block, under the priFuncs variable, you would add the following:

    funcMap := []template.FuncMap{

        Funcs: funcMap,

The render.Options map may look different if you’ve already customized the options, but what you need to do is load priFuncs in a funcMap. Then, there is no need to call anything when you run the template function, it’s automatically called. For example, something similar to this would remain unmodified:

r.HTML(200, "index", data)

Last Updated: 2015-01-19 09:29:53 +0000 UTC

What are your thoughts on this?


RSS feed

Follow Doug On Social