Home > Software engineering >  What is a template cache?
What is a template cache?

Time:09-27

I'm confused with this code that I wrote it by watching golang course. Please explain me what will *template.Template contain? It is called template cache so what is this exactly? And why config.go has TemplateCache field and RenderTemplate refers to it? I guess it is dependency injection and so far dependency injection and pointers are the most confusing things for me in golang

render.go

var functions = template.FuncMap{}
var app *config.AppConfig

// NewTemplates sets the config for the template package
func NewTemplates(a *config.AppConfig) {
    app = a
}

// RenderTemplate
func RenderTemplate(w http.ResponseWriter, tmpl string) {
    var tc map[string]*template.Template

    // if statement enables development mode
    if app.UseCache {
        //get the template cache from the app config

        tc = app.TemplateCache
    } else {
        tc, _ = CreateTemplateCache()
    }

    t, ok := tc[tmpl]
    if !ok {
        log.Fatal("couldnt get template from template cache in render.go (37)")
    }

    buf := new(bytes.Buffer)
    _ = t.Execute(buf, nil)
    _, err := buf.WriteTo(w)
    if err != nil {
        fmt.Println("Error writing template to browser in render.go (44)", err)
    }
}

// CreateTemplateCache creates template cache as a map
func CreateTemplateCache() (map[string]*template.Template, error) {
    myCache := map[string]*template.Template{}

    pages, err := filepath.Glob("./templates/*page.html")
    fmt.Println("List of all pages that matches '*page.html': ", pages)
    if err != nil {
        return myCache, err
    }

    for _, page := range pages {
        name := filepath.Base(page)
        fmt.Println("Page is currently", page)
        fmt.Println("template.New return value: ", template.New(name))

        ts, err := template.New(name).Funcs(functions).ParseFiles(page)
        if err != nil {
            return myCache, err
        }

        matches, err := filepath.Glob("./templates/*.layout.html")
        if err != nil {
            return myCache, err
        }

        if len(matches) > 0 {
            ts, err = ts.ParseGlob("./templates/*.layout.html")
            if err != nil {
                return myCache, err
            }
        }

        myCache[name] = ts
    }
    return myCache, nil
}

config.go

// AppConfig holds the application config
type AppConfig struct {
    UseCache      bool
    TemplateCache map[string]*template.Template
}

CodePudding user response:

According to the docs at pkg.go.dev Template is a struct that contains one field named Tree with type *parse.Tree. If we go to parse package we see that

Tree is the representation of a single parsed template.

As to your question about what TemplateCache is, it's as it sounds.

In computing, a cache is a high-speed data storage layer which stores a subset of data

So the TemplateCache stores template for future use and access. When RenderTemplate runs, it builds the template from scratch using the html/tmpl files to a format (template.Template) that Go can work with and render.

A naive version of the rendering would be that after every request the different handler would call a render function to build the templates after every request but what the RenderTemplate function does is that it's getting called only once in the beginning of the applications in main.go and builds all the templates and stores them in the TemplateCache for future use.

  •  Tags:  
  • go
  • Related