Documentation ¶
Overview ¶
A Django-syntax like template-engine
Blog posts about pongo2 (including introduction and migration): https://www.florian-schlachter.de/?tag=pongo2
Complete documentation on the template language: https://docs.djangoproject.com/en/dev/topics/templates/
Try out pongo2 live in the pongo2 playground: https://www.florian-schlachter.de/pongo2/
Make sure to read README.md in the repository as well.
A tiny example with template strings:
(Snippet on playground: https://www.florian-schlachter.de/pongo2/?id=1206546277)
// 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!
Index ¶
- Constants
- Variables
- func Logf(sender string, format string, items ...interface{})
- func RegisterFilter(name string, fn FilterFunction)
- func RegisterTag(name string, parserFn TagParser)
- func RenderTemplateFile(fn string, ctx Context) string
- func RenderTemplateString(s string, ctx Context) string
- func SetDebug(b bool)
- type Context
- type ExecutionContext
- type Expression
- type FilterFunction
- type IEvaluator
- type INode
- type INodeEvaluator
- type INodeTag
- type NodeWrapper
- type Parser
- func (p *Parser) Consume()
- func (p *Parser) ConsumeN(count int)
- func (p *Parser) Count() int
- func (p *Parser) Current() *Token
- func (p *Parser) Error(msg string, token *Token) error
- func (p *Parser) Get(i int) *Token
- func (p *Parser) GetR(shift int) *Token
- func (p *Parser) Match(typ TokenType, val string) *Token
- func (p *Parser) MatchOne(typ TokenType, vals ...string) *Token
- func (p *Parser) MatchType(typ TokenType) *Token
- func (p *Parser) ParseExpression() (INodeEvaluator, error)
- func (p *Parser) Peek(typ TokenType, val string) *Token
- func (p *Parser) PeekN(shift int, typ TokenType, val string) *Token
- func (p *Parser) PeekOne(typ TokenType, vals ...string) *Token
- func (p *Parser) PeekType(typ TokenType) *Token
- func (p *Parser) PeekTypeN(shift int, typ TokenType) *Token
- func (p *Parser) Remaining() int
- func (p *Parser) WrapUntilTag(names ...string) (*NodeWrapper, *Parser, error)
- type TagParser
- type Template
- type Token
- type TokenType
- type Value
- func (v *Value) Bool() bool
- func (v *Value) CanSlice() bool
- func (v *Value) Contains(other *Value) bool
- func (v *Value) EqualValueTo(other *Value) bool
- func (v *Value) Float() float64
- func (v *Value) Index(i int) *Value
- func (v *Value) Integer() int
- func (v *Value) Interface() interface{}
- func (v *Value) IsBool() bool
- func (v *Value) IsFloat() bool
- func (v *Value) IsInteger() bool
- func (v *Value) IsNil() bool
- func (v *Value) IsNumber() bool
- func (v *Value) IsString() bool
- func (v *Value) IsTrue() bool
- func (v *Value) Iterate(fn func(idx, count int, key, value *Value) bool, empty func())
- func (v *Value) Len() int
- func (v *Value) Negate() *Value
- func (v *Value) Slice(i, j int) *Value
- func (v *Value) String() string
Constants ¶
const ( TokenError = iota EOF TokenHTML TokenKeyword TokenIdentifier TokenString TokenNumber TokenSymbol )
const Version = "1.0"
Version string
Variables ¶
var ( // Available symbols in pongo2 (within filters/tag) TokenSymbols = []string{ "==", ">=", "<=", "&&", "||", "{{", "}}", "{%", "%}", "!=", "<>", "(", ")", "+", "-", "*", "<", ">", "/", "^", ",", ".", "!", "|", ":", "=", "%", } // Available keywords in pongo2 TokenKeywords = []string{"in", "and", "or", "not", "true", "false", "as"} )
Functions ¶
func RegisterFilter ¶
func RegisterFilter(name string, fn FilterFunction)
Registers a new filter. If there's already a filter with the same name, RegisterFilter will panic. You usually want to call this function in the filter's init() function: http://golang.org/doc/effective_go.html#init
See http://www.florian-schlachter.de/post/pongo2/ for more about writing filters and tags.
func RegisterTag ¶
Registers a new tag. If there's already a tag with the same name, RegisterTag will panic. You usually want to call this function in the tag's init() function: http://golang.org/doc/effective_go.html#init
See http://www.florian-schlachter.de/post/pongo2/ for more about writing filters and tags.
func RenderTemplateFile ¶
Shortcut; renders a template file directly. Panics when providing a malformed template or an error occurs during execution.
func RenderTemplateString ¶
Shortcut; renders a template string directly. Panics when providing a malformed template or an error occurs during execution.
Types ¶
type Context ¶
type Context map[string]interface{}
Use this Context type to provide constants, variables, instances or functions to your template.
pongo2 automatically provides meta-information or functions through the "pongo2"-key. Currently, context["pongo2"] contains the following keys:
- version: returns the version string
Template examples for accessing items from your context:
{{ myconstant }} {{ myfunc("test", 42) }} {{ user.name }} {{ pongo2.version }}
type ExecutionContext ¶
type ExecutionContext struct { Autoescape bool Public Context Private Context // contains filtered or unexported fields }
If you're writing a custom tag, your tag's Execute()-function will have access to the ExecutionContext. This struct stores anything about the current rendering process's Context including the Context provided by the user (field Public). You can safely use the Private context to provide data to the user's template (like a 'forloop'-information). The Shared-context is used to share data between tags. All ExecutionContexts share this context.
Please be careful when accessing the Public data. PLEASE DO NOT MODIFY THE PUBLIC CONTEXT (read-only).
To create your own execution context within tags, use the NewExecutionContext(parent) function.
func NewChildExecutionContext ¶
func NewChildExecutionContext(parent *ExecutionContext) *ExecutionContext
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, buffer *bytes.Buffer) error
func (*Expression) FilterApplied ¶
func (expr *Expression) FilterApplied(name string) bool
type IEvaluator ¶
type IEvaluator interface { Evaluate(*ExecutionContext) (*Value, error) FilterApplied(name string) bool }
type INodeEvaluator ¶
type INodeEvaluator interface { INode IEvaluator }
type NodeWrapper ¶
type NodeWrapper struct { Endtag string // contains filtered or unexported fields }
func (*NodeWrapper) Execute ¶
func (wrapper *NodeWrapper) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) error
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) 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) GetR ¶
Returns tokens[current-position + shift] or NIL (if (current-position + i) >= len(tokens))
func (*Parser) Match ¶
Returns the CURRENT token if the given type AND value matches. Consumes this token on success.
func (*Parser) MatchOne ¶
Returns the CURRENT token if the given type AND *one* of the given values matches. Consumes this token on success.
func (*Parser) MatchType ¶
Returns the CURRENT token if the given type matches. Consumes this token on success.
func (*Parser) ParseExpression ¶
func (p *Parser) ParseExpression() (INodeEvaluator, error)
func (*Parser) Peek ¶
Returns the CURRENT token if the given type AND value matches. It DOES NOT consume the token.
func (*Parser) PeekN ¶
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 ¶
Returns the CURRENT token if the given type AND *one* of the given values matches. It DOES NOT consume the token.
func (*Parser) PeekType ¶
Returns the CURRENT token if the given type matches. It DOES NOT consume the token.
func (*Parser) PeekTypeN ¶
Returns the tokens[current position + shift] token if the given type matches. DOES NOT consume the token for that token.
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 ¶
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 {
// contains filtered or unexported fields
}
func FromFile ¶
Loads a template from a filename and returns a Template instance. The filename must either be relative to the application's directory or be an absolute path.
func FromString ¶
Loads a template from string and returns a Template instance.
func Must ¶
Helper function which 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) ExecuteBytes ¶
Executes the template and returns the rendered template as a []byte
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
func ApplyFilter ¶
Applies a filter to a given value using the given parameters. Returns a *pongo2.Value or an error.
func AsValue ¶
func AsValue(i interface{}) *Value
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 ¶
Like ApplyFilter, but panics on an error
func (*Value) 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 ¶
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 ¶
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 ¶
Checks whether two values are containing the same value or object.
func (*Value) 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) 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() interface{}
Gives you access to the underlying value.
func (*Value) 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 ¶
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) Len ¶
Returns the length for an array, chan, map, slice or string. Otherwise it will return 0.
func (*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) 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:
- string
- int/uint (any size)
- float (any precision)
- bool
- time.Time
- 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.
Source Files ¶
- context.go
- doc.go
- filters.go
- filters_builtin.go
- helpers.go
- lexer.go
- nodes.go
- nodes_html.go
- nodes_wrapper.go
- parser.go
- parser_document.go
- parser_expression.go
- pongo2.go
- pongo2_options.go
- tags.go
- tags_autoescape.go
- tags_block.go
- tags_comment.go
- tags_cycle.go
- tags_extends.go
- tags_filter.go
- tags_firstof.go
- tags_for.go
- tags_if.go
- tags_ifchanged.go
- tags_ifequal.go
- tags_ifnotequal.go
- tags_include.go
- tags_lorem.go
- tags_macro.go
- tags_now.go
- tags_spaceless.go
- tags_ssi.go
- tags_templatetag.go
- tags_widthratio.go
- tags_with.go
- template.go
- value.go
- variable.go