MCPcopy
hub / github.com/valyala/quicktemplate

github.com/valyala/quicktemplate @v1.8.0 sqlite

repository ↗ · DeepWiki ↗ · release v1.8.0 ↗
361 symbols 1,221 edges 36 files 104 documented · 29%
README

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

  • Extremely fast. Templates are converted into Go code and then compiled.
  • Quicktemplate syntax is very close to Go - there is no need to learn yet another template language before starting to use quicktemplate.
  • Almost all bugs are caught during template compilation, so production suffers less from template-related bugs.
  • Easy to use. See quickstart and examples for details.
  • Powerful. Arbitrary Go code may be embedded into and mixed with templates. Be careful with this power - do not query the database and/or external resources from templates unless you miss the PHP way in Go :) This power is mostly for arbitrary data transformations.
  • Easy to use template inheritance powered by Go interfaces. See this example for details.
  • Templates are compiled into a single binary, so there is no need to copy template files to the server.

Drawbacks

  • Templates cannot be updated on the fly on the server, since they are compiled into a single binary. Take a look at fasttemplate if you need a fast template engine for simple dynamically updated templates. There are ways to dynamically update the templates during development.

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

  • All template placeholders are HTML-escaped by default.
  • Template placeholders for JSON strings prevent from </script>-based XSS attacks:

```qtpl {% func FailedXSS() %}

{% 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:

  • {%d int %} and {%dl int64 %} {%dul uint64 %} for integers.
  • {%f float %} for float64. Floating point precision may be set via {%f.precision float %}. For example, {%f.2 1.2345 %} outputs 1.23.
  • {%z bytes %} for byte slices.
  • {%q str %} and {%qz bytes %} for JSON-compatible quoted strings.
  • {%j str %} and {%jz bytes %} for embedding str into a JSON string. Unlike {%q str %}, it doesn't quote the string.
  • {%u str %} and {%uz bytes %} for URL encoding the given str.
  • {%v anything %} is equivalent to %v in printf-like functions.

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() %}:

  • {%=h F() %} produces html-escaped output.
  • {%=u F() %} produces URL-encoded output.
  • {%=q F() %} produces quoted json string.
  • {%=j F() %} produces json string without quotes.
  • {%=uh F() %} produces html-safe URL-encoded output.
  • {%=qh F() %} produces html-safe quoted json string.
  • {%=jh F() %} produces html-safe json string without quotes.

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:

  • {% comment %}

    qtpl {% comment %} This is a comment. It won't trap into the output. It may contain {% arbitrary tags %}. They are just ignored. {% endcomment %}

  • {% plain %}

    qtpl {% plain %} Tags will {% trap into %} the output {% unmodified %}. Plain block may contain invalid and {% incomplete tags. {% endplain %}

  • {% collapsespace %}

    ```qtpl {% collapsespace %}

space between lines

           and {%s "tags" %}

is collapsed into a single space unless{% newline %}or{% space %}is used

{% endcollapsespace %}
```

Is converted into:

```

space between lines

and tags

is collapsed into a single space unless or is used

```
  • {% stripspace %}

    ```qtpl {% stripspace %}

space between lines

            and {%s " tags" %}

is removed unless{% newline %}or{% space %}is used

{% endstripspace %}
```

Is converted into:

```

space between lines

and tags

is removed unless or is used

```
  • It is possible removing whitespace before and after the tag by adding - after {% or prepending %} with -. For example:

    qtpl var sum int {%- for i := 1; i <= 3; i++ -%} sum += {%d i %} {%- endfor -%} return sum

    Is converted into: var sum int sum += 1 sum += 2 sum += 3 return sum

  • {% switch %}, {% case %} and {% default %}:

    qtpl 1 + 1 = {% switch 1+1 %} {% case 2 %} 2? {% case 42 %} 42! {% default %} I don't know :( {% endswitch %}

  • {% code %}:

    qtpl {% code // arbitrary Go code may be embedded here! type FooArg struct { Name string Age int } %}

  • {% package %}:

    qtpl Override default package name with the custom name {% package customPackageName %}

  • {% import %}:

    qtpl Import external packages. {% import "foo/bar" %} {% import ( "foo" bar "baz/baa" ) %}

  • {% cat "/path/to/file" %}:

    qtpl Cat emits the given file contents as a plaintext: {% func passwords() %} /etc/passwd contents: {% cat "/etc/passwd" %} {% endfunc %}

  • {% interface %}:

    ```qtpl Interfaces allow powerful templates' inheritance {% interface Page { Title() Body(s string, n int) Footer() } %}

    PrintPage prints Page {% func PrintPage(p Page) %} {%= p.Title() %}

{%= p.Body("foo", 42) %}

{%= p.Footer() %}

        </body>
    </html>
{% endfunc %}

Base page implementation
{% code
type BasePage struct {
    TitleStr string
    FooterStr string
}
%}
{% func (bp *BasePage) Title() %}{%s bp.TitleStr %}{% endfunc %}
{% func (bp *BasePage) Body(s string, n int) %}
    <b>s={%q s %}, n={%d n %}</b>
{% endfunc %}
{% func (bp *BasePage) Footer() %}{%s bp.FooterStr %}{% endfunc %}

Main page implementation
{% code
type MainPage struct {
    // inherit from BasePage
    BasePage

    // real body for main page
    BodyStr string
}
%}

Override only Body
Title and Footer are used from BasePage.
{% func (mp *MainPage) Body(s string, n int) %}



        main body: {%s mp.BodyStr %}






        base body: {%= mp.BasePage.Body(s, n) %}



{% endfunc %}
```

See [basicserver example](https://github.com/valyala/quicktemplate/tree/master/examples/basicserver)
for more details.

Performance optimization tips

  • Prefer calling WriteFoo instead of Foo when generating template output for {% func Foo() %}. This avoids unnesessary memory allocation and a copy for a string returned from Foo().

  • Prefer {%= Foo() %} instead of {%s= Foo() %} when e

Extension points exported contracts — how you extend this code

Page (Interface)
line testdata/templates/integration.qtpl:117
testdata/templates/integration.qtpl.go
Page (Interface)
line examples/basicserver/templates/basepage.qtpl:4
examples/basicserver/templates/basepage.qtpl.go

Core symbols most depended-on inside this repo

N
called by 193
writer.go
S
called by 175
writer.go
Context
called by 54
parser/scanner.go
Printf
called by 52
parser/parser.go
Next
called by 31
parser/scanner.go
AcquireByteBuffer
called by 24
bytebuffer.go
ReleaseByteBuffer
called by 24
bytebuffer.go
Reset
called by 23
writer.go

Shape

Function 215
Method 126
Struct 17
Interface 2
TypeAlias 1

Languages

Go100%

Modules by API surface

parser/parser.go41 symbols
writer_timing_test.go37 symbols
parser/scanner.go28 symbols
writer.go24 symbols
tests/marshal_timing_test.go22 symbols
parser/parser_test.go21 symbols
testdata/templates/integration.qtpl.go20 symbols
examples/basicserver/templates/basepage.qtpl.go17 symbols
parser/scanner_test.go16 symbols
writer_test.go14 symbols
tests/templates_timing_test.go14 symbols
examples/basicserver/templates/tablepage.qtpl.go13 symbols

Dependencies from manifests, versioned

github.com/andybalholm/brotliv1.1.0 · 1×
github.com/valyala/bytebufferpoolv1.0.0 · 1×

For agents

$ claude mcp add quicktemplate \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact