Part 000 Introduction To Go Templates

Go Language ships with (in 1.1.2) an elegant and powerful pair of template processors. There is text/template and html/template. The interface to both of them is almost the same. text/template is for processing text. html/template puts a lot of effort into making safe HTML that will not allow an attacker to add malicious JavaScript, URLs or HTML code to your output.

In this set of articles I am going to delve into both packages. The goal is to make a command line tool that will allow you to test templates quickly and easily. Along the way I will extend the base template language with Go functions. Also I will look at some of the limitations of the template language and see if we can overcome them.

First a quick look at the templates.

You can change the delimiters that the templates use. Normally templates start with {{ and end with }}.

    {{.ValueFromStruct}}

Would be an example of extracting a substitution field named ValueFromStruct out of the data passed to the template processor.

    The Value = {{.ValueFromStruct}}

Given ValueFromStruct is set to "bob" this would produce "The Value = bob". The templates have the ability to iterate over sets of data, perform conditionals and substitute strings.

Another feature of these templates is that they are very, very fast. For a rough comparison I ran a quick test with 10 iterations of html/template compared to Mustache a Node.js template library. I used a 100,000 byte file with 100 substitutions in it. The Go code ran in an average of 0.21 seconds. The Node.js/Mustache code averaged 8.94 seconds.

In any case… That's enough of an intro. Let move on to some code and examples.


•       •       •       •       •       •

Summary: # of Words: 402
Author: Philip J. Schlump
Published On: 2013-10-23

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens