Golang Templates-1: Introduction

A template engine is a software application which generates dynamic HTML. This can be assumed as the view of the MVC paradigm. But, in reality, the template is exactly not view, a little bit of controller logic is added to make not too rigid.

In Golang, the handler(controller) calls the template engine, passing it the template(s) to be used, usually as a list of template files and the dynamic data. The template engine then generates the HTML and writes it to the ResponseWriter, which adds it to the HTTP response sends back to the client.

Golang HTTP Server Architecture

A template is a string or file containing one or more portions enclosed in double braces, {{…}}, called actions. These actions are processed by the template engine to produce dynamic HTML.

  1. Parse the template string/file to create a parsed template struct.
  2. Execute the parsed template, passing a ResponseWriter and some data to it.

All templates are associated with a name.

  1. Template name are defined using template.New(). In case of ParseFiles() and ParseGlob(), the first file in the argument list and the first file picked up are the names respectively. https://golang.org/pkg/html/template/#New
  2. Templates can be looked up by using the name(template.Lookup()). https://golang.org/pkg/html/template/#Template.Lookup
  3. Template name can be queried(template.Name()) https://golang.org/pkg/html/template/#Template.Name

template.Parse() method takes a string and returns a parsed structured template.

template.ParseFiles() is a variadic function call. It takes variable number arguments. template.ParseGlob() uses pattern matching.

Both of the above functions return a set of parsed templates. The returned template name will be the first file in PraseFiles() and the first file matched in the regular expression in ParseGlob(). https://golang.org/pkg/text/template/#ParseFiles

The template.Execute() method applies a parsed template to the specified data object and writes the output to an output writer.The template.ExecuteTemplate() method works if the template contains multiple parsed template object. This is shown in the previous example.

template.ExecuteTemplate() calls template.Execute() internally. It basically looks for the named template and executes that one.

In Golang library, you can see the implementation.

Error Handling

All three parse methods returns error in case of failure. The standard library provides template.Must(), which wraps around a function that returns a pointer to a template and an error, and panics if the error is not a nil.

t  := template.Must(template.ParseFiles("tmpl.html"))

While Executing, both the methods may fail and return error. But, by that time, some data might have been written to the buffer and sent back to browser. The programmer should handle this situation.

C++11/14, Qt, Juce