Home

Awesome

Build Status GoDoc Go Report Card

quicktemplate

A fast, powerful, yet easy to use template engine for Go. Inspired by the Mako templates philosophy.

Features

Drawbacks

Performance comparison with html/template

Quicktemplate is more than 20x faster than html/template. The following simple template is used in the benchmark:

Benchmark results:

$ go test -bench='Benchmark(Quick|HTML)Template' -benchmem github.com/valyala/quicktemplate/tests
BenchmarkQuickTemplate1-4                 	10000000	       120 ns/op	       0 B/op	       0 allocs/op
BenchmarkQuickTemplate10-4                	 3000000	       441 ns/op	       0 B/op	       0 allocs/op
BenchmarkQuickTemplate100-4               	  300000	      3945 ns/op	       0 B/op	       0 allocs/op
BenchmarkHTMLTemplate1-4                  	  500000	      2501 ns/op	     752 B/op	      23 allocs/op
BenchmarkHTMLTemplate10-4                 	  100000	     12442 ns/op	    3521 B/op	     117 allocs/op
BenchmarkHTMLTemplate100-4                	   10000	    123392 ns/op	   34498 B/op	    1152 allocs/op

goTemplateBenchmark compares QuickTemplate with numerous Go templating packages. QuickTemplate performs favorably.

Security

{% func FailedXSS() %}
<script>
    var s = {%q= "</script><script>alert('you pwned!')" %};
</script>
{% endfunc %}

Examples

See examples.

Quick start

First of all, install the quicktemplate package and quicktemplate compiler (qtc):

go get -u github.com/valyala/quicktemplate
go get -u github.com/valyala/quicktemplate/qtc

If you using go generate, you just need put following into your main.go

Important: please specify your own folder (-dir) to generate template file

//go:generate go get -u github.com/valyala/quicktemplate/qtc
//go:generate qtc -dir=app/views  

Let's start with a minimal template example:

All text outside function templates is treated as comments,
i.e. it is just ignored by quicktemplate compiler (`qtc`). It is for humans.

Hello is a simple template function.
{% func Hello(name string) %}
	Hello, {%s name %}!
{% endfunc %}

Save this file into a templates folder under the name hello.qtpl and run qtc inside this folder.

If everything went OK, hello.qtpl.go file should appear in the templates folder. This file contains Go code for hello.qtpl. Let's use it!

Create a file main.go outside templates folder and put the following code there:

package main

import (
	"fmt"

	"./templates"
)

func main() {
	fmt.Printf("%s\n", templates.Hello("Foo"))
	fmt.Printf("%s\n", templates.Hello("Bar"))
}

Then issue go run. If everything went OK, you'll see something like this:


	Hello, Foo!


	Hello, Bar!

Let's create more a complex template which calls other template functions, contains loops, conditions, breaks, continues and returns. Put the following template into templates/greetings.qtpl:


Greetings greets up to 42 names.
It also greets John differently comparing to others.
{% func Greetings(names []string) %}
	{% if len(names) == 0 %}
		Nobody to greet :(
		{% return %}
	{% endif %}

	{% for i, name := range names %}
		{% if i == 42 %}
			I'm tired to greet so many people...
			{% break %}
		{% elseif name == "John" %}
			{%= sayHi("Mr. " + name) %}
			{% continue %}
		{% else %}
			{%= Hello(name) %}
		{% endif %}
	{% endfor %}
{% endfunc %}

sayHi is unexported, since it starts with lowercase letter.
{% func sayHi(name string) %}
	Hi, {%s name %}
{% endfunc %}

Note that every template file may contain an arbitrary number
of template functions. For instance, this file contains Greetings and sayHi
functions.

Run qtc inside templates folder. Now the folder should contain two files with Go code: hello.qtpl.go and greetings.qtpl.go. These files form a single templates Go package. Template functions and other template stuff is shared between template files located in the same folder. So Hello template function may be used inside greetings.qtpl while it is defined in hello.qtpl. Moreover, the folder may contain ordinary Go files, so its contents may be used inside templates and vice versa. The package name inside template files may be overriden with {% package packageName %}.

Now put the following code into main.go:

package main

import (
	"bytes"
	"fmt"

	"./templates"
)

func main() {
	names := []string{"Kate", "Go", "John", "Brad"}

	// qtc creates Write* function for each template function.
	// Such functions accept io.Writer as first parameter:
	var buf bytes.Buffer
	templates.WriteGreetings(&buf, names)

	fmt.Printf("buf=\n%s", buf.Bytes())
}

Careful readers may notice different output tags were used in these templates: {%s name %} and {%= Hello(name) %}. What's the difference? The {%s x %} is used for printing HTML-safe strings, while {%= F() %} is used for embedding template function calls. Quicktemplate supports also other output tags:

All the output tags except {%= F() %} produce HTML-safe output, i.e. they escape < to &lt;, > to &gt;, etc. If you don't want HTML-safe output, then just put = after the tag. For example: {%s= "<h1>This h1 won't be escaped</h1>" %}.

As you may notice {%= F() %} and {%s= F() %} produce the same output for {% func F() %}. But the first one is optimized for speed - it avoids memory allocations and copies. It is therefore recommended to stick to it when embedding template function calls.

Additionally, the following extensions are supported for {%= F() %}:

All output tags except {%= F() %} family may contain arbitrary valid Go expressions instead of just an identifier. For example:

Import fmt for fmt.Sprintf()
{% import "fmt" %}

FmtFunc uses fmt.Sprintf() inside output tag
{% func FmtFunc(s string) %}
	{%s fmt.Sprintf("FmtFunc accepted %q string", s) %}
{% endfunc %}

There are other useful tags supported by quicktemplate:

Performance optimization tips

Use cases

While the main quicktemplate purpose is generating HTML, it may be used for generating other data too. For example, JSON and XML marshalling may be easily implemented with quicktemplate:

{% code
type MarshalRow struct {
	Msg string
	N int
}

type MarshalData struct {
	Foo int
	Bar string
	Rows []MarshalRow
}
%}

// JSON marshaling
{% stripspace %}
{% func (d *MarshalData) JSON() %}
{
	"Foo": {%d d.Foo %},
	"Bar": {%q= d.Bar %},
	"Rows":[
		{% for i, r := range d.Rows %}
			{
				"Msg": {%q= r.Msg %},
				"N": {%d r.N %}
			}
			{% if i + 1 < len(d.Rows) %},{% endif %}
		{% endfor %}
	]
}
{% endfunc %}
{% endstripspace %}

// XML marshalling
{% stripspace %}
{% func (d *MarshalData) XML() %}
<MarshalData>
	<Foo>{%d d.Foo %}</Foo>
	<Bar>{%s d.Bar %}</Bar>
	<Rows>
	{% for _, r := range d.Rows %}
		<Row>
			<Msg>{%s r.Msg %}</Msg>
			<N>{%d r.N %}</N>
		</Row>
	{% endfor %}
	</Rows>
</MarshalData>
{% endfunc %}
{% endstripspace %}

Usually, marshalling built with quicktemplate works faster than the marshalling implemented via standard encoding/json and encoding/xml. See the corresponding benchmark results:

go test -bench=Marshal -benchmem github.com/valyala/quicktemplate/tests
BenchmarkMarshalJSONStd1-4                	 3000000	       480 ns/op	       8 B/op	       1 allocs/op
BenchmarkMarshalJSONStd10-4               	 1000000	      1842 ns/op	       8 B/op	       1 allocs/op
BenchmarkMarshalJSONStd100-4              	  100000	     15820 ns/op	       8 B/op	       1 allocs/op
BenchmarkMarshalJSONStd1000-4             	   10000	    159327 ns/op	      59 B/op	       1 allocs/op
BenchmarkMarshalJSONQuickTemplate1-4      	10000000	       162 ns/op	       0 B/op	       0 allocs/op
BenchmarkMarshalJSONQuickTemplate10-4     	 2000000	       748 ns/op	       0 B/op	       0 allocs/op
BenchmarkMarshalJSONQuickTemplate100-4    	  200000	      6572 ns/op	       0 B/op	       0 allocs/op
BenchmarkMarshalJSONQuickTemplate1000-4   	   20000	     66784 ns/op	      29 B/op	       0 allocs/op
BenchmarkMarshalXMLStd1-4                 	 1000000	      1652 ns/op	       2 B/op	       2 allocs/op
BenchmarkMarshalXMLStd10-4                	  200000	      7533 ns/op	      11 B/op	      11 allocs/op
BenchmarkMarshalXMLStd100-4               	   20000	     65763 ns/op	     195 B/op	     101 allocs/op
BenchmarkMarshalXMLStd1000-4              	    2000	    663373 ns/op	    3522 B/op	    1002 allocs/op
BenchmarkMarshalXMLQuickTemplate1-4       	10000000	       145 ns/op	       0 B/op	       0 allocs/op
BenchmarkMarshalXMLQuickTemplate10-4      	 3000000	       597 ns/op	       0 B/op	       0 allocs/op
BenchmarkMarshalXMLQuickTemplate100-4     	  300000	      5833 ns/op	       0 B/op	       0 allocs/op
BenchmarkMarshalXMLQuickTemplate1000-4    	   30000	     53000 ns/op	      32 B/op	       0 allocs/op

FAQ