ZetCode

Go pongo2

last modified October 30, 2026

In this article we show how to work with templates in Go using the pongo2 template engine. Pongo2 implements the Django template language: statements in {% %}, expressions in {{ }}, comments in {# #} and filters applied with |.

The engine compiles a template into a tree once and renders it as often as needed with different contexts. Templates can be read from strings, byte slices or files, and inherited through extends and block.

All examples in this article were compiled and run with Go 1.27.0 and github.com/flosch/pongo2/v5 v5.0.0.

Installing pongo2

The module path carries the major version, so the import is github.com/flosch/pongo2/v5.

$ go mod init example.com/pongo
$ go get github.com/flosch/pongo2/v5@v5.0.0
go: added github.com/flosch/pongo2/v5 v5.0.0

The engine uses only the standard library in the code that a program links. go get records the module as an indirect requirement until a file imports it; after go mod tidy the requirement is direct and go.mod holds a single line. The module graph also lists gopkg.in/check.v1, which pongo2 uses for its own tests; it is downloaded but not compiled into the application.

Rendering a string template

pongo2.FromString parses the template text and returns a *Template or a parse error. Execute renders it with a context and returns the result as a string.

main.go
package main

import (
    "fmt"
    "log"

    "github.com/flosch/pongo2/v5"
)

func main() {

    tpl, err := pongo2.FromString("Hello {{ name|capfirst }}!")
    if err != nil {
        log.Fatal(err)
    }

    out, err := tpl.Execute(pongo2.Context{"name": "john doe"})
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(out)
}

The capfirst filter uppercases the first character only, so the result keeps the rest of the name in lower case. The context is a map[string]interface{}, which is why any value can be stored in it.

$ go run main.go
Hello John doe!

Struct fields and methods

A value in the context can be a struct. Dots in a template walk the fields and call the exported methods, so {{ user.Name }} reads the field and {{ user.Title }} calls the method.

main.go
package main

import (
    "fmt"
    "log"

    "github.com/flosch/pongo2/v5"
)

type User struct {
    Name       string
    Occupation string
}

func (u User) Title() string {
    return u.Name + ", " + u.Occupation
}

func main() {

    src := "{{ user.Name }} | {{ user.Occupation }} | {{ user.Title }}"
    tpl := pongo2.Must(pongo2.FromString(src))

    out, err := tpl.Execute(pongo2.Context{"user": User{"John Doe", "gardener"}})
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(out)
}

pongo2.Must turns a parse error into a panic. It is meant for templates that are part of the program and cannot be wrong at run time; a template read from disk at startup should still be checked with the two-value form so that the error message can be logged.

$ go run main.go
John Doe | gardener | John Doe, gardener

Loops and conditions

The for tag iterates over slices and maps. Inside the loop the forloop object exposes Counter, Counter0, First, Last and RevCounter, and if adds conditions.

main.go
package main

import (
    "fmt"
    "log"

    "github.com/flosch/pongo2/v5"
)

func main() {

    const src = `{% for w in words %}{{ forloop.Counter }}. {{ w }}{% if not forloop.Last %}, {% endif %}{% endfor %}`

    tpl, err := pongo2.FromString(src)
    if err != nil {
        log.Fatal(err)
    }

    out, err := tpl.Execute(pongo2.Context{"words": []string{"sky", "blue", "storm"}})
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(out)
}

The whole template sits on one line and uses a raw string literal, so no whitespace and no escape sequences get in the way of the output. forloop.Counter starts at one, and the condition suppresses the comma after the last element.

$ go run main.go
1. sky, 2. blue, 3. storm

Filters

A filter transforms a value and takes an optional argument after a colon. The engine ships with the Django filter set: length, upper, lower, capfirst, title, join, default, slice, truncatechars, date and many others.

main.go
package main

import (
    "fmt"
    "log"

    "github.com/flosch/pongo2/v5"
)

func main() {

    const src = "{{ word|length }} {{ word|upper }} {{ word|capfirst }} " +
        "{{ missing|default:\"n/a\" }} {{ words|join:\", \" }} {{ word|slice:\":3\" }}"

    tpl, err := pongo2.FromString(src)
    if err != nil {
        log.Fatal(err)
    }

    out, err := tpl.Execute(pongo2.Context{
        "word":  "falcon",
        "words": []string{"sky", "earth"},
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(out)
}

The filters chain from left to right and each one receives the output of the previous one. default only applies when the value is missing or empty, which makes it useful for optional context keys; the key missing is not in the context at all.

$ go run main.go
6 FALCON Falcon n/a sky, earth fal

Template files and inheritance

Templates read from disk can extend a base template. block marks a region that a child template may override, and extends must be the first tag of the child. Paths are resolved against the loader's base directory.

templates/base.html
<!DOCTYPE html>
<html>
<head><title>{% block title %}Users{% endblock %}</title></head>
<body>
{% block content %}{% endblock %}
</body>
</html>

The base file provides the document skeleton. Both blocks have default content, so the base can be rendered on its own.

templates/users.html
{% extends "base.html" %}

{% block title %}{{ count }} users{% endblock %}

{% block content %}
<ul>
{% for u in users %}
    <li>{{ u.Name }} ({{ u.Occupation }})</li>
{% endfor %}
</ul>
{% endblock %}

The child overrides both blocks and uses two context values: the slice of users and its length. The line breaks around the tags are copied verbatim on rendering.

main.go
package main

import (
    "fmt"
    "log"

    "github.com/flosch/pongo2/v5"
)

type User struct {
    Name       string
    Occupation string
}

func main() {

    if err := pongo2.DefaultLoader.SetBaseDir("templates"); err != nil {
        log.Fatal(err)
    }

    tpl, err := pongo2.FromFile("users.html")
    if err != nil {
        log.Fatal(err)
    }

    users := []User{
        {"John Doe", "gardener"},
        {"Roger Roe", "driver"},
    }

    out, err := tpl.Execute(pongo2.Context{"users": users, "count": len(users)})
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(out)
}

SetBaseDir changes the base directory of the default loader, which also affects include and extends lookups. The directory is resolved relative to the working directory of the process.

$ go run main.go
<!DOCTYPE html>
<html>
<head><title>2 users</title></head>
<body>

<ul>

    <li>John Doe (gardener)</li>

    <li>Roger Roe (driver)</li>

</ul>

</body>
</html>

HTML escaping

Output is escaped by default, which protects a page from injected markup. {% autoescape off %} disables the escaping for a region, and the safe filter marks a single value as trusted.

main.go
package main

import (
    "fmt"
    "log"

    "github.com/flosch/pongo2/v5"
)

func main() {

    comment := `<b>nice</b> & "clean"`

    auto, err := pongo2.FromString("{{ comment }}")
    if err != nil {
        log.Fatal(err)
    }

    out, err := auto.Execute(pongo2.Context{"comment": comment})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(out)

    text, err := pongo2.FromString("{% autoescape off %}{{ comment }}{% endautoescape %}")
    if err != nil {
        log.Fatal(err)
    }

    out, err = text.Execute(pongo2.Context{"comment": comment})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(out)

    raw, err := pongo2.FromString("{{ comment|safe }}")
    if err != nil {
        log.Fatal(err)
    }

    out, err = raw.Execute(pongo2.Context{"comment": comment})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(out)
}

The value in the context is the literal text <b>nice</b> & "clean". The first render escapes the angle brackets, the ampersand and the quotes; the other two print it unchanged, which is only safe for text the program controls.

$ go run main.go
&lt;b&gt;nice&lt;/b&gt; &amp; &quot;clean&quot;
<b>nice</b> & "clean"
<b>nice</b> & "clean"

Parse errors and missing values

A broken template is reported at compile time with the line, the column and the token where the parser gave up. A missing context key is not an error: it renders as an empty string.

main.go
package main

import (
    "fmt"
    "log"

    "github.com/flosch/pongo2/v5"
)

func main() {

    _, err := pongo2.FromString("{% for w in words %}{{ w }}{% endfor")
    fmt.Println(err)

    tpl, err := pongo2.FromString("{{ user.Name }}")
    if err != nil {
        log.Fatal(err)
    }

    out, err := tpl.Execute(pongo2.Context{})
    fmt.Printf("%q %v\n", out, err)
}

The error value from FromString is a *pongo2.Error whose Error() string contains the position and a short message; the type also carries the fields separately for programs that want to log them. The second template compiles, and the render succeeds with an empty result.

$ go run main.go
[Error (where: parser) in <string> | Line 1 Col 31 near 'endfor'] Unexpected EOF.
"" <nil>

Rendering in an HTTP handler

ExecuteWriter writes the rendered template to an io.Writer, which includes http.ResponseWriter. The template is compiled once, at package initialization, and reused for every request.

templates/table.html
<table>
{% for u in users %}
    <tr><td>{{ u.Name }}</td><td>{{ u.Occupation }}</td></tr>
{% endfor %}
</table>

The handler builds the data for each request and passes it in the context. The response header is not set explicitly: net/http sniffs the content type from the first bytes and detects HTML.

main.go
package main

import (
    "log"
    "net/http"

    "github.com/flosch/pongo2/v5"
)

type User struct {
    Name       string
    Occupation string
}

var tpl = pongo2.Must(pongo2.FromFile("templates/table.html"))

func usersHandler(w http.ResponseWriter, r *http.Request) {

    users := []User{
        {Name: "John Doe", Occupation: "gardener"},
        {Name: "Roger Roe", Occupation: "driver"},
        {Name: "Peter Smith", Occupation: "teacher"},
    }

    if err := tpl.ExecuteWriter(pongo2.Context{"users": users}, w); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func main() {

    http.HandleFunc("GET /users", usersHandler)

    log.Fatal(http.ListenAndServe(":8080", nil))
}

The route pattern uses the method-aware syntax of the ServeMux introduced in Go 1.22, so a POST to the same path is answered with 405. The response below was captured with curl; the Date header is left out because it changes on every request.

$ curl -si localhost:8080/users
HTTP/1.1 200 OK
Content-Length: 166
Content-Type: text/html; charset=utf-8

<table>

    <tr><td>John Doe</td><td>gardener</td></tr>

    <tr><td>Roger Roe</td><td>driver</td></tr>

    <tr><td>Peter Smith</td><td>teacher</td></tr>

</table>

Source

Go pongo2 - GitHub page

In this article we have rendered pongo2 templates from strings and files, used loops, conditions and filters, inherited blocks, controlled HTML escaping, read parse errors and served a template from an HTTP handler.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.