quicktemplate

repository·master·Indexed 25 days ago

https://github.com/valyala/quicktemplate

A high-performance Go template engine that compiles templates into Go code for speed and type safety. It is designed for high-load web applications, offering significantly lower latency and fewer allocations than the standard html/template package. The library includes the qtc compiler to convert .qtpl files into Go code and provides built-in security measures to prevent XSS attacks via HTML and JSON escaping.

Tokens
3.9K
Snippets
12
Records
28
Agent score
84%

What's inside quicktemplate

  1. Overview of quicktemplate

    master
    quicktemplate is a high-performance template engine for Go that converts templates into Go code, which is then compiled. It is designed to be extremely fast (over 20x faster than html/template), easy to use because its syntax is very close to Go, and powerful due to its ability to embed arbitrary Go code for data transformations. Templates are compiled into the final binary, eliminating the need to ship separate template files.
  2. Use go:generate to automate qtc compilation

    master

    You can automate template generation using go generate. Add the following directives to your main.go file.

    Important: You must specify your own target directory using the -dir flag to tell qtc where to generate the .go files.

    //go:generate go get -u github.com/valyala/quicktemplate/qtc
    //go:generate qtc -dir=app/views  
  3. Use interfaces for template inheritance

    master

    Quicktemplate supports template inheritance using Go interfaces. You can define an interface in a template and then implement it using {% code %} blocks and template functions.

    {% interface Page {
        Title()
        Body(s string, n int)
        Footer()
    }
    %}
    
    {% func PrintPage(p Page) %}
        <html>
            <head><title>{%= p.Title() %}</title></head>
            <body>
                <div>{%= p.Body("foo", 42) %}</div>
                <div>{%= p.Footer() %}</div>
            </body>
        </html>
    {% endfunc %}
  4. Optimize quicktemplate performance

    master

    To achieve maximum performance and minimize memory allocations, follow these best practices:

    • Use Write* methods: When generating output for a template defined as {% func Foo() %}, call WriteFoo(w) instead of Foo(). This avoids unnecessary string memory allocation and copying.
    • Use {%= ... %} for embedding: When embedding a function template, prefer {%= Foo() %} over {%s= Foo() %}. Both produce the same output, but the former is optimized for speed.
    • Use specific output tags: Avoid generic tags like {%v %} or using fmt.Sprintf inside a tag. Instead, use specific tags like {%s %} or {%d %} (e.g., use {%d num %} instead of {%s fmt.Sprintf("%d", num) %}).
    • Avoid manual string composition: Instead of building complex strings in Go code and passing them to a template, create a custom function template to handle the composition.
    • Use buffered writers: Always pass a buffered io.Writer (like bufio.Writer) to Write* functions to minimize expensive syscalls. Note: fasthttp.RequestCtx is already buffered and does not need wrapping.
    • Profile allocations: Use go tool pprof --alloc_objects to identify and fix memory-intensive functions.
  5. Generate template code using go generate

    master

    The preferred way to use qtc is via go generate. Add a //go:generate directive near your main function pointing to the directory containing your .qtpl files. qtc will recursively process all subdirectories within the specified path.

    Note: Directories containing templates can also include .go files, which allows you to use helper functions and structs defined in those files within your templates.

    package main
    
    //go:generate qtc -dir=path/to/directory/with/templates
    
    func main() {
        // main code here
    }
  6. Control whitespace with tag modifiers

    master

    You can remove whitespace immediately before or after a tag by adding a - modifier.

    • Add - after {% (e.g., {%-) to remove whitespace before the tag.
    • Prepend - to %} (e.g., -%}) to remove whitespace after the tag.
    var sum int
    {%- for i := 1; i <= 3; i++ -%}
    sum += {%d i %}
    {%- endfor -%}
    return sum
  7. Configure syntax highlighting for qtpl files in JetBrains IDEs

    master

    To enable syntax highlighting and autocomplete for .qtpl files in JetBrains products, manually add the QuickTemplate file type definition:

    1. Navigate to your JetBrains settings directory.
    2. Create a filetypes directory if it doesn't exist.
    3. Download and append the QuickTemplate.xml configuration to that directory.
    4. Restart your IDE.

    Commands:

    cd [JetBrains settings directory]
    mkdir -p filetypes && cd filetypes
    curl https://raw.githubusercontent.com/valyala/quicktemplate/master/QuickTemplate.xml >> QuickTemplate.xml