pongo2

package module
v7.0.0-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 26 Imported by: 0

README

pongo2

PkgGoDev Build Status Run on Repl.it

pongo2 is a Django-syntax like templating-language (official website).

Install/update using go get (no dependencies required by pongo2):

go get -u github.com/flosch/pongo2/v7

Please use the issue tracker if you're encountering any problems with pongo2 or if you need help with implementing tags or filters (create a ticket!).

Looking for a Go developer/consultant? I'm available for hire. 👨💻

First impression of a template

<html>
  <head>
    <title>Our admins and users</title>
  </head>
  {# This is a short example to give you a quick overview of pongo2's syntax. #}
  {% macro user_details(user, is_admin=false) %}
  <div class="user_item">
    <!-- Let's indicate a user's good karma -->
    <h2 {% if (user.karma>= 40) || (user.karma > calc_avg_karma(userlist)+5) %} class="karma-good"{% endif %}>

      <!-- This will call user.String() automatically if available: -->
      {{ user }}
    </h2>

    <!-- Will print a human-readable time duration like "3 weeks ago" -->
    <p>This user registered {{ user.register_date|naturaltime }}.</p>

    <!-- Let's allow the users to write down their biography using markdown;
             we will only show the first 15 words as a preview -->
    <p>The user's biography:</p>
    <p>
      {{ user.biography|markdown|truncatewords_html:15 }}
      <a href="/user/{{ user.id }}/">read more</a>
    </p>

    {% if is_admin %}
    <p>This user is an admin!</p>
    {% endif %}
  </div>
  {% endmacro %}

  <body>
    <!-- Make use of the macro defined above to avoid repetitive HTML code
         since we want to use the same code for admins AND members -->

    <h1>Our admins</h1>
    {% for admin in adminlist %} {{ user_details(admin, true) }} {% endfor %}

    <h1>Our members</h1>
    {% for user in userlist %} {{ user_details(user) }} {% endfor %}
  </body>
</html>

Documentation

Features

Caveats

Filters
  • date / time: The date and time filter are taking the Golang specific time- and date-format (not Django's one) currently. Take a look on the format here.
  • stringformat: stringformat does not take Python's string format syntax as a parameter, instead it takes Go's. Essentially {{ 3.14|stringformat:"pi is %.2f" }} is fmt.Sprintf("pi is %.2f", 3.14).
  • escape / force_escape: Unlike Django's behaviour, the escape-filter is applied immediately. Therefore there is no need for a force_escape-filter yet.
Tags
  • for: All the forloop fields (like forloop.counter) are written with a capital letter at the beginning. For example, the counter can be accessed by forloop.Counter and the parentloop by forloop.Parentloop.
  • now: takes Go's time format (see date and time-filter).
Misc
  • not in-operator: You can check whether a map/struct/string contains a key/field/substring by using the in-operator (or the negation of it): {% if key in map %}Key is in map{% else %}Key not in map{% endif %} or {% if !(key in map) %}Key is NOT in map{% else %}Key is in map{% endif %}.

Add-ons, libraries and helpers

Official
  • pongo2-addons - Official additional filters/tags for pongo2 (for example a markdown-filter). They are in their own repository because they're relying on 3rd-party-libraries.
3rd-party

Please add your project to this list and send me a pull request when you've developed something nice for pongo2.

Who's using pongo2

I'm compiling a list of pongo2 users. Add your project or company!

API-usage examples

Please see the documentation for a full list of provided API methods.

A tiny example (template string)
// Compile the template first (i. e. creating the AST)
tpl, err := pongo2.FromString("Hello {{ name|capfirst }}!")
if err != nil {
    panic(err)
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
out, err := tpl.Execute(pongo2.Context{"name": "florian"})
if err != nil {
    panic(err)
}
fmt.Println(out) // Output: Hello Florian!

Example server-usage (template file)

package main

import (
    "github.com/flosch/pongo2/v7"
    "net/http"
)

// Pre-compiling the templates at application startup using the
// little Must()-helper function (Must() will panic if FromFile()
// or FromString() will return with an error - that's it).
// It's faster to pre-compile it anywhere at startup and only
// execute the template later.
var tplExample = pongo2.Must(pongo2.FromFile("example.html"))

func examplePage(w http.ResponseWriter, r *http.Request) {
    // Execute the template per HTTP request
    err := tplExample.ExecuteWriter(pongo2.Context{"query": r.FormValue("query")}, w)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func main() {
    http.HandleFunc("/", examplePage)
    http.ListenAndServe(":8080", nil)
}

Documentation

Overview

Package pongo2 is a Django-syntax like template-engine

More info about pongo2: https://www.schlachter.tech/pongo2

Complete documentation on the template language: https://docs.djangoproject.com/en/dev/topics/templates/

Make sure to read README.md in the repository as well.

A tiny example with template strings:

// Compile the template first (i. e. creating the AST)
tpl, err := pongo2.FromString("Hello {{ name|capfirst }}!")
if err != nil {
    panic(err)
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
out, err := tpl.Execute(pongo2.Context{"name": "fred"})
if err != nil {
    panic(err)
}
fmt.Println(out) // Output: Hello Fred!

Package pongo2 implements a Django-syntax template engine for Go.

Index

Constants

View Source
const (
	// EOF represents the end-of-file marker used by the lexer to signal
	// that all input has been consumed. The value -1 is chosen because
	// it's an invalid rune value that cannot appear in valid UTF-8 input.
	EOF rune = -1
)
View Source
const Version = "7.0.0-alpha.1"

Version string

Variables

View Source
var (

	// TokenSymbols lists all recognized operator and punctuation symbols.
	// The slice is ordered by symbol length (longest first) to ensure
	// greedy matching: "{{-" is matched before "{{".
	//
	// Symbol categories:
	//   - 3-char: Whitespace-trimming delimiters ({{-, -}}, {%-, -%})
	//   - 2-char: Comparison ops, logical ops, template delimiters
	//   - 1-char: Arithmetic, punctuation, filter pipe, etc.
	TokenSymbols = []string{

		"{{-", "-}}", "{%-", "-%}",

		"==", ">=", "<=", "&&", "||", "{{", "}}", "{%", "%}", "!=", "<>",

		"(", ")", "+", "-", "*", "<", ">", "/", "^", ",", ".", "!", "|", ":", "=", "%", "[", "]",
	}

	// TokenKeywords lists all reserved words in the template language.
	// These cannot be used as variable or filter names.
	TokenKeywords = []string{"in", "and", "or", "not", "true", "false", "as", "export"}
)
View Source
var (

	// DefaultLoader allows the default un-sandboxed access to the local file
	// system and is being used by the DefaultSet.
	DefaultLoader = MustNewLocalFileSystemLoader("")

	// DefaultSet is a set created for you for convenience reasons.
	DefaultSet = NewSet("default", DefaultLoader)

	// FromString loads a template from string and returns a Template instance.
	// This is a convenience function that delegates to DefaultSet.FromString.
	FromString = DefaultSet.FromString

	// FromBytes loads a template from bytes and returns a Template instance.
	// This is a convenience function that delegates to DefaultSet.FromBytes.
	FromBytes = DefaultSet.FromBytes

	// FromFile loads a template from a filename and returns a Template instance.
	// This is a convenience function that delegates to DefaultSet.FromFile.
	FromFile = DefaultSet.FromFile

	// FromCache is a convenient method to cache templates. It is thread-safe
	// and will only compile the template associated with a filename once.
	// This is a convenience function that delegates to DefaultSet.FromCache.
	FromCache = DefaultSet.FromCache

	// RenderTemplateString is a shortcut and renders a template string directly.
	// This is a convenience function that delegates to DefaultSet.RenderTemplateString.
	RenderTemplateString = DefaultSet.RenderTemplateString

	// RenderTemplateFile is a shortcut and renders a template file directly.
	// This is a convenience function that delegates to DefaultSet.RenderTemplateFile.
	RenderTemplateFile = DefaultSet.RenderTemplateFile

	// RegisterFilter registers a new filter for the DefaultSet.
	// Returns an error if a filter with the same name already exists.
	RegisterFilter = DefaultSet.RegisterFilter

	// ReplaceFilter replaces an existing filter in the DefaultSet.
	// Use with caution since it changes existing filter behaviour.
	ReplaceFilter = DefaultSet.ReplaceFilter

	// RegisterTag registers a new tag for the DefaultSet.
	// Returns an error if a tag with the same name already exists.
	RegisterTag = DefaultSet.RegisterTag

	// ReplaceTag replaces an existing tag in the DefaultSet.
	// Use with caution since it changes existing tag behaviour.
	ReplaceTag = DefaultSet.ReplaceTag

	// Globals is the global context for the DefaultSet.
	// Variables added here will be available to all templates in the DefaultSet.
	Globals = DefaultSet.Globals

	// SetAutoescape configures the default autoescaping behavior for the DefaultSet.
	// When enabled (true), template output will be automatically HTML-escaped for safety.
	SetAutoescape = DefaultSet.SetAutoescape
)

Functions

func BuiltinFilterExists

func BuiltinFilterExists(name string) bool

BuiltinFilterExists returns true if the given filter is a built-in filter. Use TemplateSet.FilterExists to check filters in a specific template set.

func BuiltinTagExists

func BuiltinTagExists(name string) bool

BuiltinTagExists returns true if the given tag is registered in builtinTags. Use TemplateSet.TagExists to check tags in a specific template set.

Types

type Context

type Context map[string]any

A Context type provides constants, variables, instances or functions to a template.

pongo2 automatically provides meta-information or functions through the "pongo2"-key. Currently, context["pongo2"] contains the following keys:

  1. version: returns the version string

Template examples for accessing items from your context:

{{ myconstant }}
{{ myfunc("test", 42) }}
{{ user.name }}
{{ pongo2.version }}

func (Context) Update

func (c Context) Update(other Context) Context

Update updates this context with the key/value-pairs from another context.

type Error

type Error struct {
	Template  *Template
	Filename  string
	Line      int
	Column    int
	Token     *Token
	Sender    string
	OrigError error
}

The Error type is being used to address an error during lexing, parsing or execution. If you want to return an error object (for example in your own tag or filter) fill this object with as much information as you have. Make sure "Sender" is always given (if you're returning an error within a filter, make Sender equals 'filter:yourfilter'; same goes for tags: 'tag:mytag'). It's okay if you only fill in ErrorMsg if you don't have any other details at hand.

func (*Error) Error

func (e *Error) Error() string

Returns a nice formatted error string.

func (*Error) RawLine

func (e *Error) RawLine() (line string, available bool, outErr error)

RawLine returns the affected line from the original template, if available.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error for use with errors.Is and errors.As.

type ExecutionContext

type ExecutionContext struct {

	// When true, {{ variable }} output is HTML-escaped. Toggle with {% autoescape %}.
	// The |safe filter bypasses escaping.
	Autoescape bool

	// User-provided data from Execute(). Treat as READ-ONLY to avoid side effects.
	Public Context

	// Engine-managed scoped data (e.g., "forloop" from {% for %}, variables
	// from {% set %}, or macros). Child contexts receive a copy, enabling
	// isolated modifications.
	Private Context

	// Data shared across all contexts during a single render. Use for cross-scope
	// tag communication.
	Shared Context
	// contains filtered or unexported fields
}

ExecutionContext holds the runtime state during template rendering.

Custom tags receive this in their Execute() method. Use NewChildExecutionContext to create scoped child contexts within tags.

Context hierarchy:

  • Public: User data (READ-ONLY)
  • Private: Scoped engine data (copied per child context)
  • Shared: Global state (same instance across all contexts)

func NewChildExecutionContext

func NewChildExecutionContext(parent *ExecutionContext) *ExecutionContext

NewChildExecutionContext creates a new execution context that inherits from a parent context. The child context shares the same Public context and Shared context as the parent, but gets its own Private context (pre-populated with copies of the parent's private data). This is useful for custom tags that need to create isolated scopes while maintaining access to the template's data.

func (*ExecutionContext) Error

func (ctx *ExecutionContext) Error(msg string, token *Token) error

func (*ExecutionContext) Logf

func (ctx *ExecutionContext) Logf(format string, args ...any)

func (*ExecutionContext) OrigError

func (ctx *ExecutionContext) OrigError(err error, token *Token) error

type Expression

type Expression struct {
	// contains filtered or unexported fields
}

func (*Expression) Evaluate

func (expr *Expression) Evaluate(ctx *ExecutionContext) (*Value, error)

func (*Expression) Execute

func (expr *Expression) Execute(ctx *ExecutionContext, writer TemplateWriter) error

func (*Expression) FilterApplied

func (expr *Expression) FilterApplied(name string) bool

func (*Expression) GetPositionToken

func (expr *Expression) GetPositionToken() *Token

type FSLoader

type FSLoader struct {
	// contains filtered or unexported fields
}

FSLoader supports the fs.FS interface for loading templates

func NewFSLoader

func NewFSLoader(fs fs.FS) *FSLoader

NewFSLoader creates a new template loader that reads templates from an fs.FS filesystem. This is useful for loading templates from embedded filesystems (using Go's embed package) or any other fs.FS implementation.

func (*FSLoader) Abs

func (l *FSLoader) Abs(base, name string) string

func (*FSLoader) Get

func (l *FSLoader) Get(path string) (io.Reader, error)

type FilterFunction

type FilterFunction func(in *Value, param *Value) (out *Value, err error)

FilterFunction is the type filter functions must fulfil

type IEvaluator

type IEvaluator interface {
	INode
	GetPositionToken() *Token
	Evaluate(*ExecutionContext) (*Value, error)
	FilterApplied(name string) bool
}

type INode

type INode interface {
	Execute(*ExecutionContext, TemplateWriter) error
}

INode is the base interface for all executable template nodes. See INodeTag for template tags returned by tag parsers.

type INodeTag

type INodeTag interface {
	INode
}

INodeTag is a semantic interface for template tags returned by TagParser functions. While structurally identical to INode, it provides API clarity and future extensibility.

type LocalFilesystemLoader

type LocalFilesystemLoader struct {
	// contains filtered or unexported fields
}

LocalFilesystemLoader represents a local filesystem loader with basic BaseDirectory capabilities. The access to the local filesystem is unrestricted.

func MustNewLocalFileSystemLoader

func MustNewLocalFileSystemLoader(baseDir string) *LocalFilesystemLoader

MustNewLocalFileSystemLoader creates a new LocalFilesystemLoader instance and panics if there's any error during instantiation. The parameters are the same like NewLocalFileSystemLoader.

func NewLocalFileSystemLoader

func NewLocalFileSystemLoader(baseDir string) (*LocalFilesystemLoader, error)

NewLocalFileSystemLoader creates a new LocalFilesystemLoader and allows templatesto be loaded from disk (unrestricted). If any base directory is given (or being set using SetBaseDir), this base directory is being used for path calculation in template inclusions/imports. Otherwise the path is calculated based relatively to the including template's path.

func (*LocalFilesystemLoader) Abs

func (fs *LocalFilesystemLoader) Abs(base, name string) string

Abs resolves a filename relative to the base directory. Absolute paths are allowed. When there's no base dir set, the absolute path to the filename will be calculated based on either the provided base directory (which might be a path of a template which includes another template) or the current working directory.

func (*LocalFilesystemLoader) Get

func (fs *LocalFilesystemLoader) Get(path string) (io.Reader, error)

Get reads the path's content from your local filesystem.

func (*LocalFilesystemLoader) SetBaseDir

func (fs *LocalFilesystemLoader) SetBaseDir(path string) error

SetBaseDir sets the template's base directory. This directory will be used for any relative path in filters, tags and From*-functions to determine your template. See the comment for NewLocalFileSystemLoader as well.

type NodeWrapper

type NodeWrapper struct {
	Endtag string
	// contains filtered or unexported fields
}

func (*NodeWrapper) Execute

func (wrapper *NodeWrapper) Execute(ctx *ExecutionContext, writer TemplateWriter) error

type Options

type Options struct {
	// If this is set to true the first newline after a block is removed (block,
	// not variable tag!). Defaults to false.
	TrimBlocks bool

	// If this is set to true leading spaces and tabs are stripped from the
	// start of a line to a block. Defaults to false
	LStripBlocks bool
}

Options allow you to change the behavior of template-engine. You can change the options before calling the Execute method.

func (*Options) Update

func (opt *Options) Update(other *Options) *Options

Update updates this options from another options.

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

The parser provides you a comprehensive and easy tool to work with the template document and arguments provided by the user for your custom tag.

The parser works on a token list which will be provided by pongo2. A token is a unit you can work with. Tokens are either of type identifier, string, number, keyword, HTML or symbol.

(See Token's documentation for more about tokens)

func (*Parser) Consume

func (p *Parser) Consume()

Consume one token. It will be gone forever.

func (*Parser) ConsumeN

func (p *Parser) ConsumeN(count int)

Consume N tokens. They will be gone forever.

func (*Parser) Count

func (p *Parser) Count() int

Returns the total token count.

func (*Parser) Current

func (p *Parser) Current() *Token

Returns the current token.

func (*Parser) Error

func (p *Parser) Error(msg string, token *Token) *Error

Error produces a nice error message and returns an error-object. The 'token'-argument is optional. If provided, it will take the token's position information. If not provided, it will automatically use the CURRENT token's position information.

func (*Parser) Get

func (p *Parser) Get(i int) *Token

Returns tokens[i] or NIL (if i >= len(tokens))

func (*Parser) GetR

func (p *Parser) GetR(shift int) *Token

Returns tokens[current-position + shift] or NIL (if (current-position + i) >= len(tokens))

func (*Parser) Match

func (p *Parser) Match(typ TokenType, val string) *Token

Returns the CURRENT token if the given type AND value matches. Consumes this token on success.

func (*Parser) MatchOne

func (p *Parser) MatchOne(typ TokenType, vals ...string) *Token

Returns the CURRENT token if the given type AND *one* of the given values matches. Consumes this token on success.

func (*Parser) MatchType

func (p *Parser) MatchType(typ TokenType) *Token

Returns the CURRENT token if the given type matches. Consumes this token on success.

func (*Parser) ParseExpression

func (p *Parser) ParseExpression() (IEvaluator, error)

func (*Parser) Peek

func (p *Parser) Peek(typ TokenType, val string) *Token

Returns the CURRENT token if the given type AND value matches. It DOES NOT consume the token.

func (*Parser) PeekN

func (p *Parser) PeekN(shift int, typ TokenType, val string) *Token

Returns the tokens[current position + shift] token if the given type AND value matches for that token. DOES NOT consume the token.

func (*Parser) PeekOne

func (p *Parser) PeekOne(typ TokenType, vals ...string) *Token

Returns the CURRENT token if the given type AND *one* of the given values matches. It DOES NOT consume the token.

func (*Parser) PeekType

func (p *Parser) PeekType(typ TokenType) *Token

Returns the CURRENT token if the given type matches. It DOES NOT consume the token.

func (*Parser) PeekTypeN

func (p *Parser) PeekTypeN(shift int, typ TokenType) *Token

Returns the tokens[current position + shift] token if the given type matches. DOES NOT consume the token for that token.

func (*Parser) Remaining

func (p *Parser) Remaining() int

Returns the UNCONSUMED token count.

func (*Parser) SkipUntilTag

func (p *Parser) SkipUntilTag(names ...string) error

Skips all nodes between starting tag and "{% endtag %}"

func (*Parser) WrapUntilTag

func (p *Parser) WrapUntilTag(names ...string) (*NodeWrapper, *Parser, error)

Wraps all nodes between starting tag and "{% endtag %}" and provides one simple interface to execute the wrapped nodes. It returns a parser to process provided arguments to the tag.

type TagParser

type TagParser func(doc *Parser, start *Token, arguments *Parser) (INodeTag, error)

This is the function signature of the tag's parser you will have to implement in order to create a new tag.

'doc' is providing access to the whole document while 'arguments' is providing access to the user's arguments to the tag:

{% your_tag_name some "arguments" 123 %}

start_token will be the *Token with the tag's name in it (here: your_tag_name).

Please see the Parser documentation on how to use the parser. See RegisterTag()'s documentation for more information about writing a tag as well.

type Template

type Template struct {

	// Options allow you to change the behavior of template-engine.
	// You can change the options before calling the Execute method.
	// Includes settings like TrimBlocks and LStripBlocks for whitespace control.
	Options *Options
	// contains filtered or unexported fields
}

Template represents a parsed pongo2 template ready for execution. It holds the parsed AST (Abstract Syntax Tree) and supports template inheritance through parent/child relationships and block overrides.

Templates are created via TemplateSet methods (FromString, FromFile, etc.) and should not be instantiated directly. Once parsed, a Template can be executed multiple times with different contexts.

The execution flow is:

Template String → Lexer → Tokens → Parser → AST (root) → Execute → Output

func Must

func Must(tpl *Template, err error) *Template

Must panics, if a Template couldn't successfully parsed. This is how you would use it:

var baseTemplate = pongo2.Must(pongo2.FromFile("templates/base.html"))

func (*Template) Execute

func (tpl *Template) Execute(context Context) (string, error)

Execute executes the template and returns the rendered output as a string. This is the most commonly used execution method for simple use cases. Context can be nil for templates that don't require variables. Returns an empty string and an error if template execution fails.

func (*Template) ExecuteBlocks

func (tpl *Template) ExecuteBlocks(context Context, blocks []string) (map[string]string, error)

ExecuteBlocks executes only the specified named blocks and returns their rendered content as a map. This is useful when you need to render specific blocks without rendering the entire template, such as for AJAX partial page updates.

Parameters:

  • context: Variables available during block execution (can be nil)
  • blocks: List of block names to render

Returns a map where keys are block names and values are their rendered content. Blocks not found in the template (or its parents) are omitted from the result. The method walks up the template inheritance chain to find all requested blocks.

func (*Template) ExecuteBytes

func (tpl *Template) ExecuteBytes(context Context) ([]byte, error)

ExecuteBytes executes the template and returns the rendered output as a byte slice. Context can be nil for templates that don't require variables. Returns nil and an error if template execution fails.

func (*Template) ExecuteWriter

func (tpl *Template) ExecuteWriter(context Context, writer io.Writer) error

ExecuteWriter executes the template with the given context and writes to writer. The output is buffered internally, so nothing is written on error; instead the error is returned. This ensures atomic writes - either all output is written or none is. Context can be nil for templates that don't require variables.

For high-performance scenarios where partial writes on error are acceptable, use ExecuteWriterUnbuffered instead.

func (*Template) ExecuteWriterUnbuffered

func (tpl *Template) ExecuteWriterUnbuffered(context Context, writer io.Writer) error

ExecuteWriterUnbuffered executes the template and writes directly to the writer without intermediate buffering. This provides better performance than ExecuteWriter but with a tradeoff: if an error occurs during execution, partial output may have already been written to the writer.

Use this method when:

  • You need maximum performance
  • You're managing your own buffer pool
  • Partial output on error is acceptable for your use case

For atomic writes (nothing written on error), use ExecuteWriter instead.

type TemplateLoader

type TemplateLoader interface {
	// Abs calculates the path to a given template. Whenever a path must be resolved
	// due to an import from another template, the base equals the parent template's path.
	Abs(base, name string) string

	// Get returns an io.Reader where the template's content can be read from.
	Get(path string) (io.Reader, error)
}

TemplateLoader allows to implement a virtual file system.

type TemplateSet

type TemplateSet struct {

	// Globals will be provided to all templates created within this template set
	Globals Context

	// If debug is true (default false), ExecutionContext.Logf() will work and output
	// to STDOUT. Furthermore, FromCache() won't cache the templates.
	// Make sure to synchronize the access to it in case you're changing this
	// variable during program execution (and template compilation/execution).
	Debug bool

	// Options allow you to change the behavior of template-engine.
	// You can change the options before calling the Execute method.
	Options *Options
	// contains filtered or unexported fields
}

TemplateSet allows you to create your own group of templates with their own global context (which is shared among all members of the set) and their own configuration. It's useful for a separation of different kind of templates (e. g. web templates vs. mail templates).

func NewSet

func NewSet(name string, loaders ...TemplateLoader) *TemplateSet

NewSet can be used to create sets with different kind of templates (e. g. web from mail templates), with different globals or other configurations.

func (*TemplateSet) AddLoader

func (set *TemplateSet) AddLoader(loaders ...TemplateLoader)

func (*TemplateSet) ApplyFilter

func (set *TemplateSet) ApplyFilter(name string, value *Value, param *Value) (*Value, error)

ApplyFilter applies a filter registered in this template set to a given value using the given parameters. Returns a *pongo2.Value or an error. This is useful for applying set-specific filters, including any custom filters registered with RegisterFilter or replaced with ReplaceFilter.

func (*TemplateSet) BanFilter

func (set *TemplateSet) BanFilter(name string) error

BanFilter bans a specific filter for this template set. See more in the documentation for TemplateSet.

func (*TemplateSet) BanTag

func (set *TemplateSet) BanTag(name string) error

BanTag bans a specific tag for this template set. See more in the documentation for TemplateSet.

func (*TemplateSet) CleanCache

func (set *TemplateSet) CleanCache(filenames ...string)

CleanCache cleans the template cache. If filenames is not empty, it will remove the template caches of those filenames. Or it will empty the whole template cache. It is thread-safe.

func (*TemplateSet) FilterExists

func (set *TemplateSet) FilterExists(name string) bool

FilterExists returns true if the given filter is registered in this template set. This checks the set's filter registry, which initially contains copies of all builtin filters plus any filters registered via RegisterFilter.

func (*TemplateSet) FromBytes

func (set *TemplateSet) FromBytes(tpl []byte) (*Template, error)

FromBytes loads a template from bytes and returns a Template instance.

func (*TemplateSet) FromCache

func (set *TemplateSet) FromCache(filename string) (*Template, error)

FromCache is a convenient method to cache templates. It is thread-safe and will only compile the template associated with a filename once. If TemplateSet.Debug is true (for example during development phase), FromCache() will not cache the template and instead recompile it on any call (to make changes to a template live instantaneously).

func (*TemplateSet) FromFile

func (set *TemplateSet) FromFile(filename string) (*Template, error)

FromFile loads a template from a filename and returns a Template instance.

func (*TemplateSet) FromString

func (set *TemplateSet) FromString(tpl string) (*Template, error)

FromString loads a template from string and returns a Template instance.

func (*TemplateSet) MustApplyFilter

func (set *TemplateSet) MustApplyFilter(name string, value *Value, param *Value) *Value

MustApplyFilter behaves like ApplyFilter, but panics on an error. This uses the template set's filter registry.

func (*TemplateSet) RegisterFilter

func (set *TemplateSet) RegisterFilter(name string, fn FilterFunction) error

RegisterFilter registers a new filter for this template set.

func (*TemplateSet) RegisterTag

func (set *TemplateSet) RegisterTag(name string, parserFn TagParser) error

RegisterTag registers a new tag for this template set.

func (*TemplateSet) RenderTemplateBytes

func (set *TemplateSet) RenderTemplateBytes(b []byte, ctx Context) (string, error)

RenderTemplateBytes is a shortcut and renders template bytes directly.

func (*TemplateSet) RenderTemplateFile

func (set *TemplateSet) RenderTemplateFile(fn string, ctx Context) (string, error)

RenderTemplateFile is a shortcut and renders a template file directly.

func (*TemplateSet) RenderTemplateString

func (set *TemplateSet) RenderTemplateString(s string, ctx Context) (string, error)

RenderTemplateString is a shortcut and renders a template string directly.

func (*TemplateSet) ReplaceFilter

func (set *TemplateSet) ReplaceFilter(name string, fn FilterFunction) error

ReplaceFilter replaces an already registered filter in this template set. Use this function with caution since it allows you to change existing filter behaviour.

func (*TemplateSet) ReplaceTag

func (set *TemplateSet) ReplaceTag(name string, parserFn TagParser) error

ReplaceTag replaces an already registered tag in this template set. Use this function with caution since it allows you to change existing tag behaviour.

func (*TemplateSet) SetAutoescape

func (set *TemplateSet) SetAutoescape(v bool)

RegisterFilter registers a new filter for this template set.

func (*TemplateSet) TagExists

func (set *TemplateSet) TagExists(name string) bool

TagExists returns true if the given tag is registered in this template set. This checks the set's tag registry, which initially contains copies of all builtin tags plus any tags registered via RegisterTag.

type TemplateWriter

type TemplateWriter interface {
	io.Writer
	WriteString(string) (int, error)
}

TemplateWriter is the interface used for writing template output. It extends io.Writer with a WriteString method for efficient string writing. bytes.Buffer satisfies this interface natively.

type Token

type Token struct {
	// Filename is the name of the template file this token came from.
	// Used for error reporting to help users locate issues.
	Filename string

	// Typ indicates what kind of token this is (HTML, identifier, etc.).
	Typ TokenType

	// Val contains the actual text content of the token.
	// For TokenError, this contains the error message.
	Val string

	// Line is the 1-based line number where this token starts.
	Line int

	// Col is the 1-based column number where this token starts.
	Col int

	// TrimWhitespaces is true for whitespace-trimming delimiters ({{-, -}}, {%-, -%}).
	// When true, adjacent whitespace in HTML content should be stripped.
	TrimWhitespaces bool
}

Token represents a single lexical element produced by the lexer. Tokens are the output of lexical analysis and the input to the parser.

func (*Token) String

func (t *Token) String() string

String returns a human-readable representation of the token for debugging. Long values (>1000 chars) are truncated to show the beginning and end. Format: <Token Typ=TYPE (num) Val='value' Line=N Col=N, WT=bool>

type TokenType

type TokenType int

TokenType represents the classification of a lexer token. Each token produced by the lexer is assigned one of these types to indicate what kind of template element it represents.

const (
	// TokenError indicates a lexical error was encountered. The token's
	// Val field contains the error message describing what went wrong.
	TokenError TokenType = iota

	// TokenHTML represents raw HTML/text content outside of template tags.
	// This is any content not enclosed in {{ }}, {% %}, or {# #} delimiters.
	TokenHTML

	// TokenKeyword represents a reserved word in the template language.
	// Keywords include: in, and, or, not, true, false, as, export.
	TokenKeyword

	// TokenIdentifier represents a variable name, filter name, or tag name.
	// Identifiers start with a letter or underscore, followed by letters,
	// digits, or underscores (e.g., "user", "my_var", "_private").
	TokenIdentifier

	// TokenString represents a quoted string literal.
	// Strings can be enclosed in single or double quotes and support
	// escape sequences: \\, \", \', \n, \t, \r.
	TokenString

	// TokenNumber represents a numeric literal (integers only).
	// The lexer currently only supports integer literals; floating-point
	// numbers are handled contextually during parsing.
	TokenNumber

	// TokenSymbol represents an operator or punctuation symbol.
	// Symbols include: {{, }}, {%, %}, ==, !=, <=, >=, +, -, etc.
	TokenSymbol

	// TokenNil is reserved but currently unused.
	// FIXME: It seems like TokenNil is never used as a token. Either remove
	// TokenNil entirely or use it.
	TokenNil
)

type Value

type Value struct {
	// contains filtered or unexported fields
}

func ApplyFilter

func ApplyFilter(name string, value *Value, param *Value) (*Value, error)

ApplyFilter applies a built-infilter to a given value using the given parameters. Returns a *pongo2.Value or an error. Use TemplateSet.ApplyFilter for set-specific filters.

func AsSafeValue

func AsSafeValue(i any) *Value

AsSafeValue works like AsValue, but does not apply the 'escape' filter.

func AsValue

func AsValue(i any) *Value

AsValue converts any given value to a pongo2.Value Usually being used within own functions passed to a template through a Context or within filter functions.

Example:

AsValue("my string")

func MustApplyFilter

func MustApplyFilter(name string, value *Value, param *Value) *Value

MustApplyFilter behaves like ApplyFilter, but panics on an error. This function uses builtinFilters. Use TemplateSet.MustApplyFilter for set-specific filters.

func (*Value) Bool

func (v *Value) Bool() bool

Bool returns the underlying value as bool. If the value is not bool, false will always be returned. If you're looking for true/false-evaluation of the underlying value, have a look on the IsTrue()-function.

func (*Value) CanSlice

func (v *Value) CanSlice() bool

CanSlice checks whether the underlying value is of type array, slice or string. You normally would use CanSlice() before using the Slice() operation.

func (*Value) Contains

func (v *Value) Contains(other *Value) bool

Contains checks whether the underlying value (which must be of type struct, map, string, array or slice) contains of another Value (e. g. used to check whether a struct contains of a specific field or a map contains a specific key).

Example:

AsValue("Hello, World!").Contains(AsValue("World")) == true

func (*Value) EqualValueTo

func (v *Value) EqualValueTo(other *Value) bool

EqualValueTo checks whether two values are containing the same value or object (if comparable).

func (*Value) Float

func (v *Value) Float() float64

Float returns the underlying value as a float (converts the underlying value, if necessary). If it's not possible to convert the underlying value, it will return 0.0.

func (*Value) GetItem

func (v *Value) GetItem(key *Value) *Value

GetItem retrieves a value from a map by key or a field from a struct by name. For maps, it attempts to convert the key to the map's key type. For structs, it uses the key's string representation as the field name. Returns nil Value if the key/field doesn't exist or the type doesn't support item access.

func (*Value) Index

func (v *Value) Index(i int) *Value

Index gets the i-th item of an array, slice or string. Otherwise it will return NIL.

func (*Value) Integer

func (v *Value) Integer() int

Integer returns the underlying value as an integer (converts the underlying value, if necessary). If it's not possible to convert the underlying value, it will return 0.

func (*Value) Interface

func (v *Value) Interface() any

Interface gives you access to the underlying value.

func (*Value) IsBool

func (v *Value) IsBool() bool

IsBool checks whether the underlying value is a bool

func (*Value) IsFloat

func (v *Value) IsFloat() bool

IsFloat checks whether the underlying value is a float

func (*Value) IsInteger

func (v *Value) IsInteger() bool

IsInteger checks whether the underlying value is an integer

func (*Value) IsMap

func (v *Value) IsMap() bool

IsMap checks whether the underlying value is a map

func (*Value) IsNil

func (v *Value) IsNil() bool

IsNil checks whether the underlying value is NIL

func (*Value) IsNumber

func (v *Value) IsNumber() bool

IsNumber checks whether the underlying value is either an integer or a float.

func (*Value) IsSliceOrArray

func (v *Value) IsSliceOrArray() bool

IsSliceOrArray returns true if the value is a slice or array (not a string)

func (*Value) IsString

func (v *Value) IsString() bool

IsString checks whether the underlying value is a string

func (*Value) IsStruct

func (v *Value) IsStruct() bool

IsStruct checks whether the underlying value is a struct

func (*Value) IsTime

func (v *Value) IsTime() bool

IsTime checks whether the underlying value is a time.Time.

func (*Value) IsTrue

func (v *Value) IsTrue() bool

IsTrue tries to evaluate the underlying value the Pythonic-way:

Returns TRUE in one the following cases:

  • int != 0
  • uint != 0
  • float != 0.0
  • len(array/chan/map/slice/string) > 0
  • bool == true
  • underlying value is a struct

Otherwise returns always FALSE.

func (*Value) Iterate

func (v *Value) Iterate(fn func(idx, count int, key, value *Value) bool, empty func())

Iterate iterates over a map, array, slice or a string. It calls the function's first argument for every value with the following arguments:

idx      current 0-index
count    total amount of items
key      *Value for the key or item
value    *Value (only for maps, the respective value for a specific key)

If the underlying value has no items or is not one of the types above, the empty function (function's second argument) will be called.

func (*Value) IterateOrder

func (v *Value) IterateOrder(fn func(idx, count int, key, value *Value) bool, empty func(), reverse bool, sorted bool)

IterateOrder behaves like Value.Iterate, but can iterate through an array/slice/string in reverse. Does not affect the iteration through a map because maps don't have any particular order. However, you can force an order using the `sorted` keyword (and even use `reversed sorted`).

func (*Value) Len

func (v *Value) Len() int

Len returns the length for an array, chan, map, slice or string. Otherwise it will return 0.

func (*Value) Negate

func (v *Value) Negate() *Value

Negate tries to negate the underlying value. It's mainly used for the NOT-operator and in conjunction with a call to return_value.IsTrue() afterwards.

Example:

AsValue(1).Negate().IsTrue() == false

func (*Value) Slice

func (v *Value) Slice(i, j int) *Value

Slice slices an array, slice or string. Otherwise it will return an empty []int.

func (*Value) String

func (v *Value) String() string

String returns a string for the underlying value. If this value is not of type string, pongo2 tries to convert it. Currently the following types for underlying values are supported:

  1. string
  2. int/uint (any size)
  3. float (any precision)
  4. bool
  5. time.Time
  6. String() will be called on the underlying value if provided

NIL values will lead to an empty string. Unsupported types are leading to their respective type name.

func (*Value) Time

func (v *Value) Time() time.Time

Time returns the underlying value as time.Time. If the underlying value is not a time.Time, it returns the zero value of time.Time.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL