All notable changes to Miya Engine will be documented in this file.
The format is based on Keep a Changelog.
{% block name required %}(and{% block name scoped required %}), as in Jinja2: a required block may hold only whitespace and comments, and rendering it fails withrequired block "name" not foundunless another template in the chain also defines it.parser.BlockNode.Requiredholds the flag. See #42.runtime.UsesInheritance(node), true when a template has an{% extends %}or, for a parsed template, usessuperanywhere (a tree built in code is searched for a whole{{ super() }}only); it decides whether a template is rendered through the inheritance processor.parser.TemplateNode.MentionsSuper(withParser.MentionsSuper()), set by the parser whensuperappears in the template, andparser.SuperNode.Bare, true for asuperthat is not called. See #38.parser.CopyStatement, which copies one statement (and an if's elif branches) and shares its statement lists;parser.CloneStatementstill copies the lists at every depth.
- Breaking: a
{% block %}withoutscopedsees only the template's top-level variables (render variables, globals and top-level{% set %}), as in Jinja2: the loop variable andloopof an enclosing{% for %},{% with %}names, macro arguments and an outer block's{% set %}are no longer visible inside it. Ascopedblock sees them as before. The flag belongs to the block's position, so an override of a block in a parent's loop sees the loop variables only when the parent's block isscoped. To migrate, addscopedto the parent's{% block %}where its content (or an override) reads such a variable.parser.BlockNode.Scopedholds the flag. See #40. - The tree
InheritanceProcessor.ResolveInheritance/ResolveInheritanceWithandSuperResolver.ProcessTemplateWithSuperCalls/ResolveSuperCallsreturn may be their input itself, or share statements and statement lists with it and with the parsed templates, wheresuper()resolution changed nothing; a parent block rendered by severalsuper()calls appears once, reachable from each call. Treat the tree as read-only, and do not walk it with a plain recursive walk, which visits a shared block once per call; at asuper()cycle the tree also refers back to a block's content that contains it (#35). See #36.
-
An inheritance chain of 12 or more templates in which each level calls
super()renders, as in Jinja2, where it failed withsuper() call depth exceeded (possible infinite recursion). The error of asuper()cycle that nothing stops now names the template and the line of the statement holding thesuper()that closes the cycle:super() in block "a" renders itself in template "c" at line N: .... See #37. -
Breaking: a
super()with no parent block fails when it is rendered, withthere is no parent block called 'a' at line N, as in Jinja2, where it rendered nothing. This covers a block in a template without{% extends %}(rendered, or imported with{% import %}/{% from %}), a base block that callssuper(), and a block only the child defines. Inside a block, asuper()in a branch that is not taken still renders, and a baresuperthere is undefined, so the Jinja2 guard{% if super is defined %}{{ super() }}{% endif %}andsuper|default('')work; with strict undefined behaviour, evaluating that baresuperother than in such a test fails with the same error. The line is that of the statement holding the call. In a template without{% extends %}, asuper()anywhere in a block body (inside an expression such as{{ super()|upper }}, a{% with %},{% call %},{% filter %},{% set %}or{% autoescape %}body, or a macro defined in the block) now gives the same error instead ofsuper() call outside of block context. Remove or guard suchsuper()calls before upgrading. See #38. -
A
super()cycle through nested blocks renders when a condition stops it, as in Jinja2: with base{% block a %}A{% if x is not defined %}{% block b %}B{% endblock %}{% endif %}{% endblock %}and a child whosebholds{% for x in [1] %}{% block a scoped %}a{{ super() }}{% endblock %}{% endfor %}, miya printsaAbaAwhere it failed withsuper() in block "a" renders itself. The cycle'ssuper()renders the outer block's content when it is reached, so a guard on a loop variable or anamespacecounter decides the depth. A cycle that nothing stops still fails with that message, now after 200 levels, and the error matchesruntime.ErrMaxRecursion. Parent content holding such a cycle is built once instead of at everysuper()call, so its build no longer doubles per nesting level. See #35. -
An
{% extends %}inside{% if %}(orelif/else, nested ifs included) is run when its branch is taken, as in Jinja2, so{% if not standalone %}{% extends 'base.html' %}{% endif %}picks the parent per render; it was ignored and the template rendered without its parent. Blocks in the branches not taken still override the parent's. On import, the module's conditional or dynamic{% extends %}is followed with the module's context, so a missing parent fails the import. A template that extends twice, on render or import, fails withextended multiple times, and{% extends 1 %}fails on import as on render; both used to be accepted (render used the first parent). See #28. -
A block override that calls
super()more than once no longer doubles the merged template for every level of nested blocks: the parent block is built once and shared by itssuper()calls, so 24 nested blocks with two calls each build in under a millisecond instead of 13 seconds. AFromStringchild, which is rebuilt on every render, no longer copies every statement of the template when it callssuper(). See #36.
parser.ForNode.LoopUnused, set by the parser when nothing in a{% for %}body can readloop(noloopname, and no block, include, import or extension tag); the evaluator then does not buildloop. AForNodebuilt in Go leaves it false and getsloopas before. A Go function that takes the context and readsloopfrom it no longer finds the loop it is called in when the template never namesloop.miya.ErrRenderPanic, wrapped by the errorRender,RenderToandEnvironment.CallMacroreturn when they recover from a panic.Environment.SetFilterParams(name, params...),Environment.AddFilterWithParams(name, fn, params...)andfilters.Paramdeclare a custom filter's parameter names so templates can pass them as keyword arguments. Keywords reach the filter as ordinary positional arguments; an unfilled earlier position receives itsParam.Default, which isnilwhen unset. Alsofilters.KwArgsandruntime.KwargsFilterApplier.runtime.InheritanceProcessor.ResolveInheritanceWith, which takes the evaluator for dynamic{% extends %}.runtime.CompareNumbers,runtime.Equal,runtime.GroupTuple,filters.TestLookupand(*filters.FilterRegistry).SetTestLookup.runtime.Markup,runtime.AsMarkup,runtime.Unmark,runtime.EscapeMarkup,runtime.KeepMarkupFuncandruntime.KwArgs(filters.KwArgsis now an alias of it). Go code that type-assertedfilters.SafeValueon a|saferesult should useruntime.AsMarkup.- String methods
upper,lower,strip,lstrip,rstrip,split,replace,startswith,endswith,format,title,capitalize,join,count,find.str.formatsupports{0[key]},{0.attr},!rand!s. On a safe (Markup) string they returnMarkupandformat,replaceandjoinescape the arguments that are not safe. d.get(key, default), andget/items/keys/valueson string-to-string maps.- List methods
indexandcount, plusappend,extendandpopon lists stored with{% set %},{% with %}or in anamespace()({% do ns.items.append(x) %}). The mutating methods copy the list on the first write and never change the application's data. On any other list they fail with a hint to store it first ({% set items = items|list %}). runtime.ErrTemplateNotFoundandruntime.TemplateNotFoundError(with the missing template'sName), returned for templates the loader cannot find. A customruntime.TemplateLoaderthat returns its own errors keeps the old rule (TemplateExistsdecides).WithTruncateLeeway(n)environment option: the defaultleewayoftruncate(Jinja2'struncate.leewaypolicy). Alsofilters.TruncateFilterWithLeeway,(*filters.FilterRegistry).Replaceandruntime.RoundedFloat.runtime.ErrOutputTooLargeandruntime.SizeError, wrapped by every size-limit error.runtime.Unbox(turns the internal list box into a plain slice);runtime.ImportedNamespace.RawGetand, in the root package,Namespace.RawGetreturn the stored value without unboxing.runtime.Number,runtime.BasicValue,runtime.SortedMapKeys,runtime.SortedMapPairsandruntime.UsesReflectLookup.runtime:DictKey(the string a dict literal, subscript,intest or.get()uses for a key),Repr(Python's repr of a template value) with theReprNamespaceinterface,Indirect(dereferences pointers to values),StringKeyMap(views a map with string keys asmap[string]interface{}),BoxList,ModuleContexter(a context that can create an empty context sharing its environment, used by imports without context),EvalCompareNodeandEvalDictNode.parser:CompareNode,CompareOperandandNewCompareNode(chained comparisons such asa < b < c),DictNodeandNewDictNode,DiscardNodeandNewDiscardNode,MacroUsage(the special names a macro body references), and the tree helpersWalkStatements,ChildBodies,CloneStatementandCheckDuplicateBlocks(errors on duplicate block names, as Jinja2 does).filters:(*FilterRegistry).RegisterWithParams,SetParamsandApplyKwargsregister, declare the parameters of, and call a filter with keyword arguments;Environment.ApplyFilterKwargsdoes the same by name.ReprDataon*Namespacereturns a copy of the namespace's data forruntime.Repr.(*filters.FilterRegistry).IsBuiltin,(*branching.TestRegistry).IsBuiltinandTemplateContextAdapter.IsBuiltinFilter/IsBuiltinTesttell miya's own filters and tests from the ones added withAddFilter/AddTest.miya.RenderPanicError, with the recovered panicValueand itsStack.runtime.SprintV(fmt.Sprintf("%v", v)that prints a slice or map met again inside itself as[...]/map[...]) andruntime.FmtCycles(reports whether%vwould recurse forever on a value).runtime.MapLookup, used by thebranchingtests to read map keys the way the evaluator does, and theruntime.FilterLookupinterface (HasFilter(name) bool), implemented by contexts that can tell whether a filter is registered.TemplateContextAdapter.Child,TemplateContextAdapter.NewModuleContext,TemplateContextAdapter.HasFilterandruntime.ContextWrapper.Child: a child scope that reads through to its parent, an empty module context for imports without context, and a filter-existence check.parser.IncludeNode.WithContext/WithoutContext({% include … with context %}/without context) andparser.CallBlockNode.Parameters,Defaultsand the embeddedMacroUsage({% call(a, b=1) m() %}).runtime.InheritanceResolverand(*runtime.ImportSystem).SetInheritanceResolver: how an{% include %}resolves the included template's{% extends %}; the environment installs one, and an import system without one renders the included tree as it is.loader.IsReadError(err): true for a permission or I/O error, whichEnvironment.GetTemplateandChainLoader'sGetSource,GetSourceWithMetadataandLoadTemplatetreat as an error rather than a missing template.
InvalidateTemplate(name)also drops the cached chain (and merged template) of every template that extendsname, directly or through a middle template; a child kept rendering the old parent until the cache TTL (15 minutes) orClearCache.super()in a block inside an extending template's top-level{% for %}or{% with %}(or in a grandchild's override of such a block) renders the parent block where the block runs and in the parent's slot; it failed withsuper() call outside of block context.- A
{{ super() }}outside every block of an extending template or its parents (in a top-level macro, call block, set block or filter block) fails when it is evaluated, as in Jinja2 (UndefinedError: 'super' is undefined). In a parent template it rendered empty, so a template that relied on that now errors. - A block has its own variable scope, as in Jinja2: a
{% set %}or macro inside a block is no longer visible after it or in later blocks, andsuper()renders the parent block in a scope of its own, so neither block sees the other's variables. Variables set outside the block andnamespace()attributes are still shared. A template that set a variable inside a block to read it elsewhere (for example{% block title %}{% set page_title = 'X' %}{% endblock %}with the layout printingpage_title) now gets an undefined value; set it at the child's top level or in anamespace(). super()renders the parent block with the child's overrides of the blocks nested inside it, as in Jinja2: a child that extendsheadwith{{ super() }}and overridestitlegets its own title. Asuper()inside such a nested block now renders that block's own parent. Asuper()cycle through nested blocks fails when it is rendered.super()works inside an expression, as in Jinja2:{{ super()|upper }},{{ super() ~ '!' }}, a macro argument,{% set p = super() %},{% if super() %}and{% elif %}. The parent block renders each time such asuper()is evaluated and not on a branch that is not taken. It used to fail withsuper() call outside of block context.- A block tag left open at the end of a template (
{% if %}without{% endif %}, and so on) reports the line where the template ends; it saidline 0, column 0. {% import %}and{% from … import %}of a template that is missing or cannot be read name it once; the error saidfailed to load template "x"twice.{% include %}of a template that is missing or cannot be read names it once; the error saidincluded template "x" not found: failed to load template "x"orfailed to load included template "x": failed to load template "x".{% import %}and{% from … import %}of a template whose{% extends %}parent (or any template further up) is missing, fails to parse or extends itself now fail, as in Jinja2; the import succeeded and exported the child's macros. The parent's top-level code still does not run. A parent named by an expression is not loaded.ChainLoader.LoadTemplatestops at a template that exists but cannot be read or does not compile, likeGetSource; it used to return a later loader's copy.enumerate(items, start=n)starts atn; it used to ignorestart=and any start that was not a Goint(a negative literal,int64). A non-integer start, an unknown keyword or a third argument is an error.- An included template that extends another renders through its base, as in Jinja2: its blocks fill the base,
super()works, and a missing parent is an error even withignore missing. It used to render only its own blocks. - A template loaded by name whose
{% extends %}names a fixed parent reuses its merged template across renders instead of rebuilding it each time (a two-level page withsuper()allocated 4.5× the same page written flat; now about the same). The merged template is cached with the template's hierarchy, per autoescape setting, and dropped with it byInvalidateTemplateof that template or of any template in its chain,ClearInheritanceCache,ClearCacheand the cache TTL.FromStringtemplates and a dynamic{% extends expr %}still rebuild on every render. - Macro calls,
for … iffilters and list and dict comprehensions no longer copy every variable in scope per call or per item; their cost no longer grows with the number of keys in the render data. A recursiveloop()no longer formats its children into an unused string (which also calledString()on Go values in them). Behaviour change: a macro defined inside another macro and called after the outer call returns (stored in a namespace, appended to a list, passed tocaller()) now reads the enclosing scope's current values, as in Jinja2, instead of the values at the time the outer macro was called. replacewith a safe argument on a number or boolean, andmapwith safe arguments over number and list items, keep the safe text, as in Jinja2.- Typed Go maps with string keys look keys up the same way through
[],inand.get()(noneis"None");range,lipsum, list+,batch,sliceandformatwidth/precision limit errors wrapErrOutputTooLarge;wordwrapaccepts a{% set %}block as its width again.[],inand.get()on a map with interface keys (as YAML decoders produce) find a key that is the key itself, the same number in another numeric type (or bool 0/1), or itsDictKeyspelling (1.0finds1;1finds a"1"key;nonefinds a"None"key; aMarkupkey and a plain string find each other), without scanning the map. A lookup that misses no longer copies or sorts the map: 100 misses on a 20 001-entry map took 2.7 s.- Keys of other Go types in hand-built interface-key maps (
int8,int32,uint,float32, named-string types andRoundedFloat) are found only by a key of the same Go type, no longer by value equality. A named-string lookup key also finds aMarkupkey. Pointer keys are never found, because the lookup key is dereferenced. [],in,is inand.get()on any Go map look the key up without scanning or copying the map, and agree with each other:- a bool key is found by
true/falseor by 0/1; - an array key is found by a list whose items equal its elements;
- any other key type (struct, pointer) is found only by a value of that type, compared with Go
==.
- a bool key is found by
- It used to be value equality, which changes three cases:
- pointer fields in struct keys are now compared by address;
map[*int]Vis no longer found by the number;- a number inside an array key with interface elements must have the same Go type.
- On int64 and uint64 maps, a float at or beyond 2^63 (2^64 for uint64) no longer finds the largest keys. This matches Jinja2.
.get('5')on a 20 000-entrymap[int]inttook about 23 ms per call;.get()on any string-key typed map copied the map;'5' is in mon a typed map failed the render.- A
[]bytekey now finds a typed string-key map's entry through.get()as well. Onmap[string]interface{}it still misses everywhere. - Pointer keys are dereferenced in
[],in,.get()and dict literals ({p: 1}has the key'1', not an address). - An undefined key finds the
""entry of a string-key or interface-key map in[],.get()andin(Jinja2: not found).
- Under autoescape, safe values stay safe through
mapwith a filter ([s]|map('upper')),map(attribute=…, default=s),default(s),loop.cycle(s, …),join(d=s)andjoin(…, attribute=…), and through+with a Go named string type. v|replace(old, new)with a safeoldornewescapesvfirst, as Jinja2 does.- A safe value repeated with
*stays safe under autoescape. - Undefined values print as
Undefinedinside lists and dicts, and maketojsonfail as in Jinja2 instead of emitting miya's internal fields. -7is an integer.- The data strings
inf,nanandinfinityare not numbers in arithmetic or in numeric filters (w * 2repeats them,w - 1andw|absare errors;w + 1concatenates in lenient mode). - zipreport-go's own
jsonfilter swallows errors, so{{ {'a': nope}|json }}now printsnullinstead of miya's internal fields. - A
nonedict key printsNone, and a rounded number finds its integer key. RoundedFloat's Go fields are no longer template attributes.{{ super() }}renders the parent block with the parent's autoescape setting.map(filter)under autoescape runs the filter once per item;map('0')on list items reads the index again when autoescape is on;map('join', s)over a mix of lists and safe strings no longer errors with autoescape on (with autoescape off it andmap('reverse')over such a mix still error; Jinja2 renders them). With autoescape on,[v, s]|map('reverse')works. For a list that mixes re-applied and other items, the other items' filter calls now run first, which can change the order of side effects and which error surfaces. A filter registered under a digit name such as"0"loses to the index on list items with autoescape on (Jinja2 calls the filter).- A macro (or
caller()) can change a list passed to it, as in Jinja2:{% do l.append(x) %}inside the macro changes the caller's list. Lists passed from render data are copied, so application data is never changed. - Go functions that take a
runtime.Context, andNamespace.Get/GetAttr/All()andImportedNamespace.Get, see plain lists, never the internal box type.RawGetreturns the raw value. - An attribute chain passed to a macro, a list method or a namespace lookup (
m(l.pop().a.b)) is evaluated once. - An imported template now runs its whole top-level body, as Jinja2 does:
- tuple and attribute
{% set %},{% do %}andforloops take effect; - only the taken
{% if %}branch runs; - module macros can append to the module's lists;
- names starting with
_(macros included) are not exported, andfrom ... import _xis an error.
- tuple and attribute
- Macros and
{% set %}inside{% for %},{% with %}and{% block %}bodies of a module are no longer exported, as in Jinja2. - Output the module prints is still discarded.
- Filters now treat Go pointers, named types (
type Status string,type Score float64,type Flag bool) and typed maps the way expressions already did:map/sort/sum/groupby/selectattr/attron lists of struct pointers used to give empty or zero results silently;int/float/round/abs/sumon named numbers gave 0 or an error;max/sort/uniquefailed on named strings;dictsort/items/.keys()failed on maps with non-string keys, and the sequence filters wrapped a map as one item instead of using its keys;dictsort(by='value')compared numbers as strings.
- Undefined values are false in
select/rejectand in boolean filter arguments. - With autoescape on,
%rand%ain a safe format string (<a title='%r'>) left the quotes raw,%cturned a number into a raw<, and a Go numeric or bool value with aString()orFormatmethod skipped escaping as an argument offormat,replaceandjoin; a safe input given towordwrapwith a plain wrapstring spliced it raw between the attributes of a tag. All are escaped now. truncatemeasured the HTML-escapedendwhen cutting, and escaped a safeend; it now measures the raw text and keeps a safeend, and an untruncated safe value stays safe.lengthandleewayaccept a{% set n %}20{% endset %}number.- Typed Go maps, slices and arrays work in templates:
m.key,m['key'],m[1],for k in m,for k, v in m,m.keys(), negative indexes, and thejoin,reverse,batch,items,keys,valuesanddictsortfilters. Maps with string keys decoded from YAML (map[interface{}]interface{}) work too. Maps with non-string keys iterate in a fixed order (bools, numbers, then strings). - Maps with a named key type, unhashable keys in
inorm[...], and struct fields reached through a nil embedded pointer no longer crash the render; a pointer that points to itself no longer hangs it. - Arithmetic (
+ - * / **, unary-) works with every Go numeric type and named numeric types. user.namefinds the struct fieldName, as documented.- Indexing, slicing, iterating,
firstandlaston strings work on characters instead of UTF-8 bytes:{{ "açúcar"[1] }}printsç, notÃ. - Slices with a negative step follow Python's bounds:
{{ s[10::-1] }}no longer panics on a string or list shorter than 11, ands[:-10:-1]includes the first element. - Bad data and malformed templates return errors instead of panicking or crashing the process:
nilin+,+on lists of different element types, nil functions (called or iterated),{% extends %}with a non-string (also in a parent template), mismatched-%}/-}}, negativetruncate/truncatehtmllength, hugecenter/pad_left/pad_right/indent/batchsizes, NaN and infinitecurrency, a crash in the trim-blocks pass, and templates nested more than 500 levels deep (previously a fatal stack overflow).Render,RenderToandCallMacrorecover any other panic as an error wrappingErrRenderPanic. Template.Release()no longer corrupts cached templates. A releasedFromStringtemplate used to render its raw source, a releasedGetTemplatetemplate rendered nothing, and releasing a base template changed its children's output.- Dict literals keep their contents:
{% set d = {'k': 'v'} %}{{ d.k }}printsv(it printed nothing, and every dict literal was empty). Each evaluation builds a new dict, so writes into one no longer carry over to the next render. Keys are stored as strings, as for every miya dict, so{1: 'a'}[1]and{1: 'a'}['1']find the same entry, and a list key such as{[1, 2]: 'x'}is stored under"[1 2]"instead of raising an error as Jinja2 does. - With autoescape on, values that are not strings (named string types, errors,
fmt.Stringers, lists, maps, structs) are escaped on output; a*runtime.SafeValueis treated as safe;{{ bytes }}prints a[]byteas text (escaped) instead of[60 98 62].urlize,urlizetruncate,nl2brandtruncatehtmlescape their input text.xmlattroutput is no longer double-escaped.tojsonescapes'.{% autoescape %}blocks keep their setting insideforloops and{% with %}.urlize(..., nofollow=true)no longer adds an extranofollowto every link after the first. - Concurrent renders on one
Environmentthat import templates no longer race or crash (concurrent map writes). {% from x import name %}for a missing name gives an undefined value whose call fails with "does not export the requested name", not placeholder text.- Macros see their own file's top-level
{% set %}variables, including block sets ({% set x %}...{% endset %}). - An imported template's own
import/fromstatements run, so its macros can call the helpers it imports. - A self-import or mutual import fails with
runtime.ErrMaxRecursioninstead of returning a half-built module. from ... import a as bworks in templates that use{% extends %}.with context/without contextparse, including after a trailing comma infrom ... import a, with context.- Filters honour keyword arguments, bound by name to Jinja2's parameters:
sort(reverse=true),map(attribute="name", default="-"),sum(attribute="price", start=10),round(precision=1),join(d=", ", attribute="n"),int(base=16),truncate(length=…)and more. They used to be silently ignored. trim(chars=none)strips whitespace, as in Jinja2.- Custom filters and tests, and keyword arguments to filters, work inside
{% autoescape %}blocks. A custom filter or test used there failed withunknown filter/unknown test. {% for … if … %}…{% else %}runs the else block when the filter leaves no items.loop.depthcounts recursion levels only (nested ordinary loops are each depth 1; recursive calls go 1, 2, 3…), andloop.depth0exists.- Recursive loops apply their
iffilter at every level. - A
forloop in a template without a parent that callssuper()keeps itsiffilter andrecursiveflag. - The
loopobject is no longer reused across loops and renders (a storedloopshowed another loop's values, and concurrent renders raced on it);AddGlobal,AddExtensionandConfigureInheritanceCacheno longer race with renders; an extension is visible only after itsOnLoadsucceeds; inheritance-cache cleanup and loader statistics are race-free;NewTemplateCachewith a negative size no longer panics;ConcurrentTemplateRendererno longer panics on a secondStop, rejectsRenderAsyncbeforeStart, and answers jobs pending atStop. - Templates from miya's loaders (
FileSystemLoader,EmbedLoader,StringLoader,ChainLoader,LRUFileSystemLoader) are compiled with the environment's settings:trim_blocks,lstrip_blocks,{{-/-}}, custom delimiters and extensions used to be ignored for them (they were, and still are, honoured for GetSource-only loaders). - Security:
FileSystemLoaderwithfollowLinksfalse (the default) reads templates throughos.Root, so no path or symlink can leave the search path. Before, only a symlink in the last path component was rejected, solinkdir/x.htmlcould read files outside the template folder (on Windows a directory junction was not detected at all). - Template names are checked per segment, like Jinja2's
split_template_path:a..b.htmlis a valid name, any..segment is rejected (a/../bused to be accepted), and on POSIX a backslash is an ordinary character. LoadTemplateon a loader without a parser returns an error instead of panicking.FileSystemLoader.LoadTemplatere-parses a template whose file modification time changed. This affects directLoadTemplatecallers only: anEnvironmentcaches compiled templates itself and does not re-read files (useClearCache/InvalidateTemplate).- Macro keyword arguments bind by name for local, imported and from-imported macros; defaults can use earlier parameters;
varargsandkwargswork; a parameter without a default and not passed is undefined instead of an error. - Imported macros can call themselves and macros from their own file, and work in
{% call %}. {% call(args) macro() %}parses and passes arguments to the block;caller()is rendered on each call.- An
{% autoescape %}block's setting applies inside macro and call-block bodies defined in it. - Runaway macro recursion reports the depth limit once instead of wrapping it at every level.
- Data containing
%}followed by blank lines no longer panics with trim_blocks. {% elif %}branches of a base template were dropped when a child extended it.- Two
FromStringtemplates extending different parents rendered the first one's output. ClearCachenow also clears the inheritance cache, so changed parent templates are reloaded when the loader serves the new source. A loader's own cache (FileSystemLoader,EmbedLoader,LRUFileSystemLoader) is separate: call itsClearCachetoo.- Rendering a template that uses
extendsno longer formats the whole context on every render (9.8 ms → 8.5 µs with a 20 000-row context). map("filtername", args...)applies the filter to each item, keyword arguments included.groupbygroups have.grouperand.list, the grouper keeps its type, andgroupby(attr, default=...)works;map(attribute="grouper"),selectattr("grouper", ...)andsort(attribute="grouper")work on groups.sort(attribute="a,b")sorts by several attributes.- The
trueandfalsetests exist (selectattr("paid", "true")); theintest compares numbers by value. - Collection filters accept strings, dicts (their keys, sorted) and typed Go slices.
- The
eq/equalto/netests compare like==(JSON1equals1, lists element by element); the aliases==,!=,<,<=,>,>=,lessthan,greaterthanexist. {% filter %}blocks no longer write filter arguments unescaped ({% filter format(u) %}%s{% endfilter %}).- Breaking: in non-HTML escape contexts (
ContextWrapperwith JS, CSS, URL or JSON), only|safe/|marksaferesults bypass the context escaper.nl2br,urlize,|e,tojsonand the other HTML filters are escaped for the context;{{ d|tojson }}in a JS context, raw before, is now JS-escaped. Use|tojson|safeto emit JSON raw there. - An
{% autoescape %}block inside a non-HTMLContextWrapperkeeps that context's escaper. - In XML/XHTML contexts, concatenation,
joinand filter arguments escape with the XML escaper. - An imported template (also
with context) escapes by its own setting, not the importer's{% autoescape %}block. - A recursive
loop()result is safe or plain according to the context of the loop itself, not of the call site ({% autoescape true %}{{ loop(x.c) }}{% endautoescape %}in an autoescape-off loop escapes the inner output). - In non-HTML escape contexts, Markup items in a list returned by a filter (
[u]|map('e')) are plain strings, so the context escaper runs on them. joiner()keeps a safe separator (joiner('<br>'|safe)) instead of falling back to,.- Tests take one argument without parentheses (
x is divisibleby 3);is in,is true,is false,is filterandis testwork; a test registered asfilterortestreplaces the built-in meaning. - Keywords can be attribute names (
d.if,d.block) and, exceptand/or/not/is/in/if/else, variable names in expressions and{% set %}(not yetfortargets, macro parameters or keyword-argument names); identifiers may be non-ASCII (not NFKC-normalized);b.0andL.0.1index. - Number literals accept
_,0x/0o/0band exponents (1e3); adjacent string literals join;(1, 2),(),set a, b = 1, 2,set (a, b) = ...andfor v in 1, 2parse;{{ a if b }}withoutelseis undefined whenbis false;[x for x in items if x > 5](and the dict form) filter. - A comparison chain evaluates each operand once and stops at the first false comparison.
includeaccepts Jinja2'signore missingbeforewith context/without context;without contexthides the render's variables.- Deeply nested
not/-chains returntemplate nesting too deepinstead of crashing. - Long flat chains (
1 + 1 + ...,a or b or ...,~,**,x|f|f|...,a.b.b...) count towards the 500-level parse limit and returntemplate nesting too deepinstead of overflowing the stack when the template is rendered. - Printing a self-referencing list or dict prints
[...]instead of crashing the process. Printing one container is capped at 64 MiB. - Strict mode:
default,d,is defined,is undefinedandis noneaccept undefined values;{{ a|default }}prints empty. x['k'] is definedandx['k']|default(…)no longer fail whenxisNoneor not subscriptable; the item counts as undefined, as in Jinja2.include none ignore missingrenders nothing.is definedis true for a key whose value isNone, andNone is undefinedis false.- An undefined value is an empty sequence for
length,join,sum,sort,list,in,itemsand the other collection filters (by filter name, so a custom filter registered under one of these names also receives[]);max/min/randomof it are undefined;tojsonof it is an error instead of internal fields. includeaccepts a list of names and renders the first that exists.{% with %}without assignments is accepted.lower/uppertests follow Python ('' is loweris false, numbers are neither);true is number; a dict is a sequence.intparses'3.7',' 7 ','1e3','1_000'and base prefixes like Jinja2, and returns the default for floats outside the 64-bit range (they printed-9223372036854775808); an invalid base falls back like Jinja2 instead of erroring;floataccepts surrounding whitespace and returnsinffor'1e400'.format_numberreturns an error for infinite or NaN values instead of printing+,Inf.centerdefaults to 80 and pads like Python.format_numberandcurrencyno longer put a separator after the minus sign (-123456|format_numberprinted-,123,456).}},%}and custom end delimiters no longer end a tag while a(,[or{opened in it is still open, as in Jinja2:{{ {'a': {'b': 2}}.a.b }}renders2, and a block end of}works with dict literals.wordcountcounts words like Jinja2 (\w+), so punctuation and hyphens separate words.- Errors from filter blocks and template inheritance keep their cause, so
errors.IsfindsErrOutputTooLargeand other sentinels through them. wordwrapon long words, hyphenated runs or long runs of spaces, andurlizeon long runs of brackets or trailing punctuation, used to be quadratic: inputs of 200-400 KB took 5-22 s. Both are now linear, and their output is unchanged.- In non-HTML escape contexts, string methods on a safe value (
.replace,.format,.join,.upper, …) return plain strings that the context escaper escapes, also inside{% autoescape false %}; they returned HTML-escapedMarkupthat was written raw.replaceand the other markup-preserving filters on a safe value no longer escape their arguments twice there. - Runaway recursion through macro default arguments or includes reports the depth limit once instead of wrapping it at every level.
- A list or dict that contains itself no longer crashes the process with a stack overflow when used as a dict key, compared with
==orin, printed inside a struct, or passed tosort,unique,min,max,dictsort,pprint,is in,is loweroris upper, or used as a key on an undefined value. - Rendering one
Contextfrom several goroutines no longer races, andContext.All()reflects later writes to parent contexts. GetTemplateno longer returns aFromStringtemplate for its internal cache name, and aFromStringhash collision can no longer return another source's template.forloops inside{% autoescape %}blocks or aContextWrapperno longer copy every context variable on each iteration.- The
replace,joinandformatfilters enforce the 64 MiB result limit (errors wrapruntime.ErrOutputTooLarge), as the string methods already did.tojson(indent)is bounded by the same limit; a huge indent no longer panics, and an indent of 0 or less puts items on separate lines, as in Jinja2. randompicks a random item (or whole character) and accepts typed slices; it always returned the first item (or byte). An empty sequence gives undefined.- Filters and tests accept pointers to slices and maps, and typed maps:
first,last,list,length,sort,unique,sum,xmlattr,is in,is sequence,is mappingandis iterable. urlizetruncateno longer double-escapes safe input.- The JSON and CSS escape contexts write control characters as valid escapes (
\u0001,\1); they wrote\uor\xfollowed by the raw character. loop.changedcompares values like==, as in Jinja2:1and1.0(ortrueand1, or a named Go string type and the plain string) are the same value.- A float literal beyond float64's range (
1e400) is infinity, as in Python, instead of a compile error. NewConcurrentTemplateRendererwith a worker count below 1 runs one worker; with 0 workersRenderAsyncandStophung forever, and a negative count panicked.
ConcurrentTemplateRenderer.RenderAsyncreturns<-chan RenderResultwith exportedOutputandErr; the old result type's fields could not be read outside the package.- Breaking: a
{% block %}body and an{% include %}d template render with the environment's autoescape setting, as in Jinja2. An{% autoescape %}tag around the block or include no longer applies to it, in the template that defines it or in a child's override. Tags inside the block body or included template still apply. Move such a tag inside to keep the old output. A block inside a{% call %}body under{% autoescape false %}is now escaped twice, as in Jinja2. With autoescape off, an{% autoescape true %}tag around a block or include no longer escapes it. - Breaking: an error in an imported module's top-level code (for example an undefined attribute in
{{ }}) now fails the import, where it used to be skipped. - Go functions that take a
runtime.Contextreceive a wrapper that unboxes lists; reach the original context withinterface{ Unwrap() runtime.Context }. Code that type-asserts the context to*miya.TemplateContextAdapter,*runtime.ContextWrapperorruntime.ContextAwareContextnow getsok == false. - Docs: a section on memory and untrusted templates.
- Extension tags inside a macro that evaluate with
CreateEvaluateFunc's raw context now see the internal box for list parameters (they saw a plain slice before); unbox withruntime.Unbox. Lists passed through the deprecatedenv.CallMacropath still cannot be appended to. - The list model is now documented: see "Lists" in
docs/DO_STATEMENTS_IMPLEMENTATION.md. time.Durationand other named integers are numbers inint,float,sumandround(a duration gives nanoseconds instead of 0).%cin a safe format string ('%c'|safe|format(60)) is now an error, as in Jinja2; it used to turn a number from data into a raw<.format,truncateandwordwrapreceive their input and arguments unchanged under autoescape and mix safe and plain text themselves. Go callers ofFormatFilter,TruncateFilterandWordwrapFilterthat passruntime.Markupgetruntime.Markupback (truncatewith a safeendescapes the plain text). Under autoescape off or outside the HTML family they are unchanged. A safe input with a plain wrapstring that is not whitespace (wordwrap(5, false, ' onerror=x ')) now gives a plain string, escaped when printed, as in Jinja2; a whitespace-only wrapstring such as'\n', or none, keeps the safe result (Jinja2 returns plain there).{% filter wordwrap(…, '<br>') %}now escapes its whole body (Jinja2 prints it raw).- Deliberate differences from Jinja2 here:
%x,%oand%Xformat a number in a safe format string (markupsafe raises a TypeError); safe input with a safe wrapstring keeps the input's markup raw, so wrapping can split escaped entities and attribute values (it only matters with a safe wrapstring containing a quote but no>);%rof a safe argument prints the repr of its text, notMarkup(...). - Breaking:
urlize(trim_url_limit, nofollow, target, rel, extra_schemes)follows Jinja2. Links getrel="noopener", combined withrelandnofollowand sorted. Trailing punctuation stays outside the link,www.and e-mail addresses are linked, and URLs are not shortened unlesstrim_url_limitis given. The first argument used to be a boolean that trimmed at 40 characters. - Breaking:
urlizetarget(miya-only) produces the same links: they getrel="noopener"and are no longer shortened to 40 characters. - Breaking:
urlencodeencodes strings with%20and no longer encodes/, so it is not safe for building a single path segment:'../admin'|urlencodestays../admin(it was..%2Fadmin). Dicts and lists of pairs become query strings. urlizeHTML-escapes itstargetandrelvalues and omits an emptytarget.titlelowercases the rest of each word and capitalizes after-and brackets:'ACME corp'|titleis nowAcme Corp. In a{% filter title %}block this applies to the markup too:<a href="/About-Us">read more</a>becomes<A Href="/about-Us">read More</a>, as in Jinja2.striptagscollapses whitespace to single spaces and removes comments.- Breaking:
wordwrap(width, break_long_words, wrapstring, break_on_hyphens)follows Python'stextwrap, as Jinja2 does. Long words are broken (passbreak_long_words=falseto keep them), words split after hyphens, runs of spaces inside a line are kept, andwidthdefaults to 79. The second argument isbreak_long_words; it used to bebreak_on_hyphens. - Breaking: a nil pointer prints as empty, is false in
{% if %}, isnone, and is treated likenonebydefault; it printed<nil>and was true. A non-nil pointer to a string, number, bool, slice or map behaves as the value it points to (it printed a memory address). Zero values of named bool, string and number types (type Flag bool) are false in{% if %}and indefault(x, true), named bools and strings compare equal to plain ones, and named strings and numbers passis string/is number. - Breaking: booleans are numbers in arithmetic and comparison, as in Python:
true + 1is2andtrue == 1is true (both used to fail or be false). - Go methods are not callable from templates. The docs used to promise zero-argument method calls, which never worked; they now say so. Pass computed values as data, or register a global function.
- Breaking: iterating a dict yields its keys, as in Jinja2:
{% for k in d %}(and comprehensions,{% set a, b = d %}) used to yield the values. Used.values()for values.{% for k, v in d %}still yields (key, value) pairs. Loops that unpack list-of-dict items into two variables ({% for a, b in list_of_dicts %}) now get each dict's two keys, as in Jinja2; useitem.fieldinstead. - Dicts are walked in sorted key order (
for,.items(),.keys(),.values()), so output no longer changes between renders. The order is code-point order, as Python'ssorted(): uppercase before lowercase, accented letters afterz, and"10"before"9". This is a deliberate difference from Jinja2, which uses insertion order: Go maps have none. dictsortis deterministic: keys (or values) that compare equal case-insensitively are ordered by code point, then by key. Jinja2 orders such ties by insertion order.- Breaking:
range()over more than 1,000,000 items,lipsum()over 1000 paragraphs or sentences, list+producing more than 10,000,000 items,batchfilling past 1,000,000 items, padding filters past 64 MiB andindentoutput past 64 MiB return an error; templates nested deeper than 500 levels fail to parse. A parent template whose{% extends %}is not a string literal is an error (it used to look up a template named<<DYNAMIC>>). These limits stop single huge allocations; they do not bound a render's memory or time. Template.Release()now removes the template from the environment's template cache and leaves it usable. A laterFromString/GetTemplateof the same source or name parses it again. The parser no longer pools AST nodes.- Breaking: a filter, global or data value that relied on a non-string type to bypass autoescape (for example Go's
html/template.HTML) is now escaped; returnruntime.SafeValueinstead.filters.SafeValueis now an alias ofruntime.SafeValue.xmlattrrejects attribute names containing whitespace,/,>or=.nl2brandurlizeescape their input text even with autoescape off (filters cannot see the setting;urlizematches Jinja2). A truncatedtruncatehtmlresult is escaped text, including theendargument. - Breaking:
and/orreturn one of their operands and skip the right side when the left decides, as in Jinja2:{{ name or 'default' }}prints the name, nottrue;{% if x != 0 and 10 / x %}no longer raises; templates that printed{{ a or b }}expectingtrue/falsenow print a value. - Breaking: imported templates run without the importer's context, as in Jinja2.
{% import %}and{% from %}macros no longer see render variables or variables set before the import. Write{% import "x.html" as x with context %}(orfrom ... import ... with context) to keep the old visibility. Imports with context are built fresh each time, so a loop no longer reuses the first iteration's values. - Breaking: importing a template that does not exist, or one with a syntax error, is an error. Previously both rendered silently.
- Breaking: a top-level
{% set %}in an imported template that fails to evaluate (for example a strict-mode undefined variable) fails the render. Previously the variable silently held the text[Variable x from file]. - Within one render, every import of a template without context shares one module, as in Jinja2 (an imported
namespace()counter keeps counting across imports in a loop). Imports with context are built fresh each time. Unlike Jinja2, modules are never shared between renders. Importing a template that{% extends %}another runs only the child's top level: the parent's top-level macros and{% set %}are not exported, whereas Jinja2 exports them. {{ x is defined }}is false whenxholds an undefined value ({% set x = nope %}), as in Jinja2. In strict mode, printing a name that a{% from %}import did not find raises an error.runtime.ImportSystem.LoadTemplateNamespaceuses the context it is given as the module context, without cloning it, writes to it, and expects the loader to return an error for a missing template (TemplateExistsis not consulted). An import on an evaluator that has no import system (for example one an extension creates withruntime.NewEvaluator()) is an error instead of binding placeholder macros.- Breaking: a keyword argument a filter cannot honour is an error instead of being ignored: an unknown name, or any keyword on a filter without declared parameters, including custom filters. Declare a custom filter's parameters with
Environment.SetFilterParamsorEnvironment.AddFilterWithParams; the error message says so. - Breaking:
sum,minandmaxtake positional arguments in Jinja2's order:sum(attribute, start)andmin/max(case_sensitive, attribute).l|sum(10)used to mean start=10 and is now an error; writel|sum(start=10).l|max("n")used to mean attribute="n"; writel|max(attribute="n"). - Breaking: a positional filter argument after a keyword argument (
join(d="-", ",")) is a syntax error, as in Jinja2. A repeated keyword still binds the last value, as in Jinja2. - Breaking:
//and%follow Python: they floor instead of truncating (-7 // 2is-4,-7 % 3is2), keep float operands (7.5 % 2is1.5,10 // 0.3is33), accept every Go numeric type, and reject strings ("10" // 3used to be3). With JSON data, where every number is a float,n // 2is now a float, so(n // 2) is integeris false, as in Jinja2. - Breaking: each for-loop iteration starts from the scope outside the loop, as in Jinja2: a
{% set %}in the loop body no longer carries over to the next iteration, and a recursiveloop(...)call no longer sees the calling iteration'ssets. Usenamespace()to accumulate across iterations. - Breaking: assigning an attribute (
{% set x.y = ... %}) works only onnamespace()objects, and item assignment ({% set x[k] = ... %}) is an error, as in Jinja2; templates can no longer modify the caller's maps, slices, structs, or Go values that merely haveGet/Setmethods (embedruntime.NamespaceMarkerto opt a type in).NewTemplateCache(0)disables the cache and a negative size means unbounded. - Breaking:
Environment.GetTemplatereads every template throughGetSourceand compiles it itself; anAdvancedLoader'sLoadTemplateis no longer used by the environment. CustomAdvancedLoaders must return the template text fromGetSourcefor every nameLoadTemplateaccepts. - Breaking: a lexer configuration set on a loader's parser (
loader.NewDirectTemplateParserWithConfig,SetLexerConfig) no longer affects rendering through anEnvironment. Set delimiters and whitespace options on theEnvironmentinstead. - Breaking: with
followLinksfalse, a symlink inside the search path is followed only if it is relative and resolves inside the search path. An absolute symlink, or one that leaves the folder, is "template not found" (setSetFollowLinks(true)to follow every link, as before for directories). A relative symlinked file inside the folder is now accepted; it used to be rejected. - Breaking: in a
ChainLoader, a template that exists in an earlier loader but does not compile is an error; it used to fall through to a later loader's copy. LRUFileSystemLoader's size and TTL bound only its ownLoadTemplatecache; they do not bound what anEnvironmentcaches.- Breaking: a macro body no longer sees the caller's local variables (loop variables, and
{% set %}inside the calling macro or loop body). As in Jinja2, it sees its parameters and the scope where it was defined. Pass values as arguments. A{% set %}inside a{% block %}is still visible to macros called from that block, because miya blocks share the top-level context (unchanged). - Breaking: an unknown keyword argument, a keyword that repeats a positional argument, or more positional arguments than parameters is an error, unless the macro uses
kwargs/varargs. - Breaking: a missing argument without a default is undefined, not an error.
- Breaking:
{% call %}on a macro that never callscaller()is an error. - Breaking:
caller()inside a call block nested in a macro no longer reaches the outer macro's caller; it fails withno caller defined, as in Jinja2. - Breaking:
{% call %}must be followed by a call ({% call w()|upper %}is a parse error,expected call), and a macro or call-block parameter namedcallermust have a default. - Breaking: a parameter named
varargsorkwargsis an ordinary parameter and turns the catch-all off, as in Jinja2. - Breaking (Go): macros are
*runtime.Macrovalues (Call(args, kwargs)), so Go code that type-asserted a macro to afuncmust use the new type.{{ m }}prints<Macro 'm'>. Each lookup of an imported macro returns a new value, som.s is sameas m.sis now false. - Breaking (Go): a Go function used in
{% call %}receives the caller differently. Afunc(...interface{})gets a trailingmap[string]interface{}holdingcaller; afunc(Context, ...interface{})no longer findscallerin its context. - Breaking: whitespace control is done by the lexer and matches Jinja2:
- a comment on its own line no longer joins the lines around it, and inline comments keep the spaces around them;
-, trim_blocks and lstrip_blocks no longer act inside string literals,{% raw %}or data;- lstrip_blocks applies on the first line;
{%+,+%},{#+and+#}are supported;\r\nand\rin templates become\n;- one trailing newline of the template is removed unless keep_trailing_newline is set (before, only when another whitespace option was on);
-markers now work in templates loaded throughStringLoaderorFileSystemLoader.
- Breaking:
{% raw %}content is output verbatim; it used to lose spaces, quotes and comments. - Breaking:
Renderno longer rewrites its output: whitespace inside<option>is kept, and data containing%}or{%keeps its blank lines and indentation.RenderandRenderTonow produce the same output. - Breaking: the
whitespacepackage is removed. - Breaking: CRLF and CR line endings in templates always become LF. There is no option to keep them (miya has no
newline_sequence), so templates that must emit CRLF (MIME, CSV, ICS) need it produced from data or a filter. - Breaking: code that builds its own
lexer.LexerConfig—loader.NewDirectTemplateParserWithConfig,DirectTemplateParser.SetLexerConfig,extensions.CreateTokensFromString— now gets that config's trim_blocks, lstrip_blocks and keep_trailing_newline applied (they were ignored), CRLF normalized, and the template's trailing newline removed unless the config setsKeepTrailingNewline. Templates rendered through anEnvironmentuse the environment's options instead. {% raw +%}is rejected with an error, as in Jinja2.- Breaking: blocks inside
if/elif/else,for,with,macro,filter,setblocks,callandautoescapecan be overridden by a child template, andsuper()works there. A block nested inside a child's block override also overrides the parent's block of that name. - Breaking: a child template's top-level code runs before its parent's, as in Jinja2: its
set,macro,importandifstatements take effect, and text before{% extends %}is output. After{% extends %},{{ }}and text are still not output (and not evaluated), but{% include %},{% call %},filterblocks and blocks insidefor/with/autoescapenow run and print before the parent's output; a missing include there is now an error. - Breaking: a root template's
{% import %}/{% from %}is no longer moved to the top: a block that uses an import written after it fails, as in Jinja2. Move imports above the blocks that use them. - Breaking: two blocks with the same name in one template are an error (
block 'a' defined twice), also when they sit in differentif/elsebranches, as in Jinja2; such templates now fail to load. - Breaking: a dynamic
{% extends expr %}follows the environment's undefined behaviour: in strict mode an undefined name inexpris anUndefinedError. {% block name scoped %}is accepted.- Breaking:
sort,min,maxandgroupbycompare numbers numerically (true/falsecount as 1/0), strings case-insensitively (unlesscase_sensitive) and lists element by element, like Jinja2; comparing a number with a string is an error that names the attribute.[10, 9, 2]|sortused to give10, 2, 9. None(JSONnull) and missing attributes never fail a sort:sortandgroupbyput them first, as one group (last withreverse), andmin/maxskip them. This deliberately differs from Jinja2, which raisesTypeError.- Breaking:
uniqueis case-insensitive by default and keeps1and"1"apart. - Breaking:
min/maxwithattribute=return the item, not the attribute; on an empty list they return undefined (prints nothing) instead of failing. - Breaking:
slice(n, fill_with)splits a list into n columns, as in Jinja2. It used to slice from index n. - Breaking:
select,reject,selectattrandrejectattrapply the named test (select("odd"),selectattr("n", "gt", 1)); they used to ignore it. An unknown test name is an error. - Breaking:
map("x")applies the filterxto items that have no attributex(words|map("upper")). Items that have the attribute still map it (a miya extension; Jinja2 always applies the filter). With keyword arguments,map("round", precision=1)always applies the filter. - Breaking: attribute names are paths, as in Jinja2:
attribute="c.name"looks upnameinsidec, and"0"indexes a list. A map key that itself contains a.is no longer found. - Breaking (Go API):
SortFilterandUniqueFilterreturn[]interface{}for[]stringinput;GroupByFilterreturns[]interface{}ofruntime.GroupTupleinstead of[][]interface{}. - Breaking: under autoescape, the output of macros,
caller(), recursiveloop(),{% set %}...{% endset %}and{% filter %}blocks is safe Markup, as in Jinja2. It is no longer escaped a second time, so templates can drop|safeon macro calls (keeping it is harmless). - Breaking:
|safe,|e/|escape,|forceescape,|urlize,|nl2br,|truncatehtml,|xmlattr,|tojson(and the other safe-producing filters) returnruntime.Markupinstead offilters.SafeValueorstring.{{ "<"|e }}is no longer double-escaped. - Breaking: a
{% filter %}block's result is escaped unless it is Markup. Jinja2 writes it raw. A custom filter that produces HTML for a filter block must returnruntime.Markuporruntime.SafeValue. - Filters applied to a safe value escape their arguments where the result stays safe (
replace,format,center,default, ...), as markupsafe does:{{ ('<b>%s</b>'|safe)|format(u) }}escapesu. - A macro's output is safe only if autoescape was on where the macro is defined. Jinja2 decides at the call site.
- Go filters, tests and Go global functions receive a plain
stringfor safe values; macros and the built-innamespace,dict,cyclerandjoinerkeep receiving Markup. - A Go filter that returns
runtime.SafeValueor*runtime.SafeValuestill works; the value becomes Markup. - Breaking: operator precedence follows Jinja2:
-2 ** 2is4,2 ** 3 ** 2is64,-x|absis(-x)|abs, and comparisons chain (a < b < cisa < b and b < c, so"apple" in fruits == trueisfalse). - Breaking:
~binds tighter than+and-:'Page ' ~ n + 1is('Page ' ~ n) + 1, which printsPage 11forn = 1(it printedPage 2), anda + b ~ cisa + (b ~ c). Write'Page ' ~ (n + 1). - Breaking:
isapplies to the operand right before it:x + 1 is divisibleby(3)isx + (1 is divisibleby(3))anda == 1 is sameas(true)isa == (1 is sameas(true)). Write(x + 1) is divisibleby(3). - Breaking (extensions):
ParserAdapter.ParseArgumentsuses the new expression grammar: adjacent string arguments join ({% tag "a" "b" %}gets one argument,"ab"), and keywords such asasare names. - To find affected templates:
grep -nE '~[^}%]*[-+]|[-+][^}%]*~' -r templates/(~mixed with+/-) andgrep -nE '[-+*/%<>=][^}%]* is ' -r templates/(isafter an operator). - Breaking: lists and dicts print like Python:
['a', 'b'],{'k': 1}, withTrue/False/Noneinside them (top-leveltrue/false/empty are unchanged). Dicts print in sorted key order. Under autoescape the printed form is HTML-escaped, as in Jinja2. - Breaking: values with an
Error()orString()method print through it inside lists and dicts too, and a[]byteinside a list prints as a quoted string. - Breaking:
*with a string literal repeats it, as in Python ('ab' * 3isababab;[1] * 2repeats a list too), even when it looks like a number:'0' * 3is000and'3' * 2is33(it used to be6). A numeric string from data still multiplies as a number. d.items()returns a list of[key, value]pairs (in sorted key order), so|list,|lengthand printing work.- Breaking:
{% include %}renders in a copy of the includer's context:{% set %}inside the included template no longer changes the includer. - Breaking:
include … ignore missingignores only a template that does not exist. An included template that fails to compile or to render, or that includes a missing template itself, is an error. - Breaking:
{% with a = …, b = … %}evaluates every value in the scope outside the block, as Jinja2 does:b = asees the outera. The order used to be random. - Breaking:
lt/le/gt/getests fail onNoneand on a string compared with a number;even/odd/divisiblebyfail on strings and no longer truncate floats. - Breaking: in strict mode,
o['missing']and an out-of-range index are errors, and so isa.b is definedwhenais undefined. - Breaking:
truncatefollows Jinja2. Strings up to 5 characters over the length are kept whole (leeway), so output can be up tolength + 5characters; passleeway=0where the text must fit, such as a table cell in a PDF, or set it for the whole environment withmiya.WithTruncateLeeway(0). The end marker counts toward the length, the default length is 255, and a length shorter than the marker is an error. The word cut no longer stops at half the length:'A Supercalifragilistic order'|truncate(16)isA.... - Breaking:
indent(width, first, blank): the third argument is Jinja2'sblank(it used to be an indent string; pass a string aswidthinstead), blank lines are not indented unlessblank, andwidthdefaults to 4. - Breaking:
roundwith a precision returns a number instead of a string.- It prints exactly as before:
10|round(2)is10.00, and rounding is half away from zero. - It now works in comparisons, arithmetic,
is numberand|int. tojsonemits2.68, not"2.68".- Go code calling
filters.RoundFiltergets aruntime.RoundedFloat; so do custom filters and global functions that receive a rounded value. - Templates that treated the result as a string change:
x|round(2) == '0.00'is now false (compare with0),x|round(2) < 'a'is an error,|lengthis an error,|firstand|listno longer split it into characters, andis string/is iterable/is sequenceturn false. inf|round(2)|tojsonis an error (JSON has no infinity; it was"+Inf").round(0)(or no precision) of a value of 1e16 or more prints in exponent form, like any float (1e20|roundprints1e+20; it printed100000000000000000000).- An unknown
methodis an error. A precision above 308, or one that overflows the value, returns it unchanged (it printedNaNor+Inf), and a value whose scaled form is beyond 2^53 is no longer distorted (1e20|round(3)printed99999999999999983616.000).
- It prints exactly as before:
filesizeformatprintskBand1 Byte, truncates below 1 kB, and goes up to YB/YiB.- Unbalanced brackets are now reported by the lexer, with Jinja2's wording:
{{ (1 }}giveslexer error in template ...: unexpected '}', expected ')'(wasparser error ...: expected ')' after expression), and a stray closer such as{{ x) }}or the typo{{ x }<div>givesunexpected ')'/unexpected '}'. A bracket left open at the end of the template, or at an end delimiter that cannot close it (such as%>), is reported where it was opened:unexpected '%>', expected ')' (opened at line 2, column ...). Code that matches on the old error text needs updating. - Custom extension tags whose arguments contain unbalanced punctuation (for example
:-)) now fail in the lexer. Jinja2 rejects them too. - Error columns on lines after the first are one higher than the actual column (an existing quirk, unchanged here); line numbers are exact.
- Breaking:
formatuses Python%formatting instead of Go'sfmt.'%d'|format(x)and'%i'|format(x)accept float operands such as JSON numbers, truncating them as Python does.%(name)stakes keyword arguments, and%r,%i,%uand%awork. Too few or too many arguments,%dof a string and a lone%are errors instead of printing%!text. Go-only verbs such as%vand%qare errors. miya differences:%x/%o/%X/%cand*accept whole floats, and%sprintsNoneas empty and booleans astrue/false. - A recovered render panic is a
*RenderPanicError(stillerrors.Is(err, ErrRenderPanic)); the goroutine stack is in itsStackfield instead of the error message.ConcurrentTemplateRendereruses it too, and its panic message changed from "panic during template render". - Breaking:
sumis an error fornoneand for items that are neither numbers nor numeric strings instead of skipping them (numeric strings still add, like miya's1 + "2"; Jinja2 raises a TypeError);replaceis an error for a count that is not a whole number (2.0is accepted,1.5and"2"are not);first,lastandlistare errors for a value that is not iterable (listused to wrap it in a one-item list). - Breaking: integer arguments (widths, counts) outside Go's
intrange are errors instead of wrapping around, e.g.pad_left(1e19). - Breaking: the undefined result of
random,first,last,minandmaxon an empty sequence follows the environment's undefined behavior, as Jinja2'senvironment.undefineddoes. WithUndefinedStrictit is an error wherever an undefined variable would be: printed, in an operator, condition or loop, as a filter, function or macro argument, as a list or dict item, or assigned with{% set %}or{% with %}; onlydefault/d(also later in a{% filter %}block's chain) and thedefined,undefinedandnonetests accept it. The undefined items ofmap([[]]|map('first')) follow the same behavior; withUndefinedStrict,joinandsumfail on them.UndefinedDebugprints its placeholder.firstandlastof an empty sequence give undefined instead ofnone(([]|first) is definedandis noneare false;[[]]|map('first')|listprints[Undefined]). - Breaking: with autoescape off in an HTML-family context, filters keep a safe input safe as markupsafe does (
upper,lower,capitalize,trim,center,indent,reverse,last,string,default,format,truncate,escape, andmapwith them), and a safe result such asx|estays safe, so a value{% set %}there is no longer escaped (again) when printed with autoescape on.center's fill is escaped, as markupsafe'sMarkup.centerescapes it, and so isindent's string, where Jinja2 inserts it as it is (a deliberate difference);trim's characters are not, as in Jinja2. Whether autoescape is on or off,defaulton a safe input returns its argument as it is, as Jinja2'sdo_defaultdoes, instead of marking it safe or turning it into an escaped string:""|safe|default(x, true)is escaped when printed, and""|safe|default(items, true)is still a list.replace,title,wordwrap,join,urlizeandxmlattr, and miya'snl2br,truncatehtml,urlizetruncateandurlizetarget, still return plain text with autoescape off, as Jinja2's do. - Breaking: in a non-HTML escape context (JS, CSS, URL or JSON through
runtime.ContextWrapper), the output of a macro,caller(), a block{% set %},loop()and a{% filter %}block is no longer escaped a second time when printed, and a filter block no longer escapes its literal text. That output stays escaped through~and+(a safe operand there is escaped for the context:Markupis HTML-safe only),safe,upper,lower,capitalize,center,indentandstring,trimwithout arguments, the argument-lessupper,lower,capitalize,strip,lstripandrstripmethods (trimand the strips not in CSS, where they would drop the space that ends an escape), and as the inputdefaultreturns; their arguments, safe ones included, are escaped for that context even with autoescape off. A case change leaves JS and JSON escape sequences such as\u003cintact. Other filters (titleamong them), indexing and slicing see its text as plain text, which is escaped again; in another escape context it is plain text too. Built-in filters and tests take it as it is inside lists and dicts, so[s]|firstprints it escaped once. Go code (filters and tests added withAddFilter/AddTest, also throughmap,selectand friends, functions andKeepMarkupFuncs, a function's context,runtime.Unbox,Namespace.Get) receives it as a plain string, also inside lists and dicts;Namespace.RawGetreturns the value as stored, for the runtime. Lists and dicts are scanned for it only when Go code gets them in a render that made some, and byruntime.UnboxandNamespace.Getonce any render made some; a scan that finds none allocates nothing. - Infinite and NaN floats print
inf,-infandnanas in Python (top-level output,~,string,join,format,round). They printed Go's+Inf,-InfandNaNoutside lists. Go code callingruntime.FormatFloat,runtime.ToStringorfilters.ToStringgets the new spelling too. Named Go float types (except inside lists),pprintandfilesizeformatstill print Go's spelling. - Breaking: two strings joined with
+always concatenate, as in Jinja2:'5' + '1'is51(it was6),'1e3' + '1'is1e31, and numeric strings from data (a + bwitha = "5",b = "1") concatenate too, as do|safestrings when autoescape is off. Convert first (a|int + b|int) to add them. A string and a number still add as numbers ('5' + 1is6), and-,*and/still treat two numeric strings as numbers ('5' - '1'is4). - Docs: string + number coercion (
'5' + 1is6,'a' + 1isa1) is listed as a deliberate difference from Jinja2. - Breaking: a template that exists but cannot be read (permission denied, an I/O error) is an error, as in Jinja2:
Environment.GetTemplateno longer reports it asruntime.ErrTemplateNotFound(the error wraps the loader's error, soerrors.Is(err, fs.ErrPermission)works),include … ignore missingno longer skips it, andChainLoader.GetSourcestops at it instead of trying the next loader. A custom loader must return (or wrap with%w) the underlying error for this to apply; any other loader error still counts as "not found".
- Breaking: unused code that no render path reached: the
inheritancepackage;runtime.OptimizedEvaluator,CachedEvaluator,BatchEvaluation,MemoryEfficientContext,FilterChainOptimizer,OptimizedFilterEvaluator,BatchFilterEvaluation,FilterPipelineandFastEvalNode;parser.FastEvaluatorand theFastEvalmethods onparser.TextNode,LiteralNode,CommentNodeandRawNode; the memory helpers inmemory_optimization.go(MemoryOptimizedContext,StringInterner,ByteBufferPool,MemoryProfiler,MemoryEfficientTemplate,PrecomputedHash,SmallStringOptimizer,CachedEnvironmentOptions,DefaultCachedOptions,MemoryStats,GetMemoryStatsand their globals);macros.MacroFunc,macros.MacroRegistry.Importandmacros.MacroContext; andruntime.ContextHasher,InheritanceCache.GetResolvedTemplateandStoreResolvedTemplate(unused since template inheritance stopped caching per-context results). Rendering output is unchanged. - Breaking:
runtime.ControlFlowEvaluator,runtime.NewControlFlowEvaluator,runtime.NestedLoopEvaluator,runtime.NewNestedLoopEvaluatorandruntime.LoopInfo: a second loop and condition evaluator that no render path used, with semantics that differed from both Jinja2 and miya's evaluator (oneloopobject shared by every iteration,{% set %}carried across iterations).runtime.LoopControlError,NewBreakErrorandNewContinueErrorstay.
runtime.DictItems: nothing creates it sinced.items()returns a list. It will be removed in a later minor release.Environment.GetMacro,ListMacros,CallMacroandClearMacros, and themacrospackage behind them. The registry mixes macros from every compiled template and binds arguments differently from template calls. They will be removed in a later minor release. To call a macro, render a template that imports it ({% from "lib.html" import m %}{{ m(x) }}), or walkTemplate.AST().parser.ReleaseAST,parser.ReleaseNode, theparser.Release*Nodefunctions,parser.GetNodePoolStatsandparser.NodePoolStatsdo nothing.filters.SelectFilter,RejectFilter,SelectAttrFilterandRejectAttrFilter: templates no longer use them (the registered filters apply tests); they keep their old value-comparing behaviour for direct Go callers.filters.AutoEscapeFilter, registered as theautoescapefilter: templates cannot call it (autoescapeis a keyword) and Jinja2 has no such filter. Useescape(filters.EscapeFilter); Go callers ofEnvironment.ApplyFilter("autoescape", ...)keep working for now.InheritanceCache.SetResolvedTTL(does nothing), theresolvedTTLargument ofEnvironment.ConfigureInheritanceCache(ignored),runtime.ResolvedTemplateCacheEntryandCacheStats.ResolvedCache(always zero).
- Breaking: the
==,!=,<,<=,>,>=,inoperators compare numbers of any Go numeric type correctly. Previously a float64 (e.g. from JSON) compared wrongly against an int literal:0 == 0.0was false and(1 - 1) > 0was true. Integers compare exactly. Comparing a string with a number using</>is now an error, as in Jinja2, and numeric strings compare as strings ("10" < "9"). - Breaking: floats print like Jinja2 in output,
~concatenation, and thestring,joinandefilters: no thousands separators, no rounding to two decimals, no scientific notation below 1e16. Whole floats still print without a decimal part. Useformat_numberorcurrencyfor formatted amounts.
- Includes, macro calls (including default arguments) and recursive loops nested more than 200 levels deep return
runtime.ErrMaxRecursioninstead of crashing the process with a stack overflow.ignore missingdoes not hide it. - Removed two test-only output rewrites: author links were stripped from templates named
blog_post(or whose output containsblog-post), and empty imported macros returned debug text.
tojsonfilter now returnsruntime.SafeValueinstead of a plain string, preventing HTML auto-escaping of JSON output. This matches Jinja2'stojsonbehavior which returnsMarkup(a safe string). Previously, when auto-escaping was enabled,{{ data | tojson }}inside<script>blocks would produce HTML-escaped entities (e.g.,"became"), resulting in invalid JavaScript since browsers do not decode HTML entities in raw text elements like<script>.- Fixed data race in concurrent template rendering.
- Template engine core: Lexer, parser, AST, and runtime evaluator pipeline.
- Template inheritance:
{% extends %},{% block %},{{ super() }}with multi-level support. - Control structures:
{% if %}/{% elif %}/{% else %},{% for %}withloopvariable,{% set %},{% with %}. - Expressions: Arithmetic, comparison, logical, membership (
in/not in), string concatenation (~), ternary (a if cond else b), power (**), floor division (//). - 70+ built-in filters: String, numeric, collection, HTML/security, date, and encoding filters.
- 26+ built-in tests: Type tests (
number,string,mapping, etc.), value tests (defined,none,true,false), numeric tests (even,odd,divisibleby), container tests (iterable,sequence), and string tests (upper,lower). - Macros:
{% macro %},{% import %},{% from ... import %}with default parameters. - Template includes:
{% include %}withignore missingsupport. - List and dictionary comprehensions:
[expr for x in list],{k: v for x in list}, with filter and expression support. - Global functions:
range(),dict(),cycler(),joiner(),namespace(),lipsum(),zip(),enumerate(),url_for(). - Filter blocks:
{% filter upper %}...{% endfilter %}. - Do statements:
{% do expression %}. - Raw blocks:
{% raw %}...{% endraw %}. - Autoescape control:
{% autoescape %}...{% endautoescape %}with HTML auto-escaping enabled by default. - Whitespace control:
{%-,-%},{{-,-}}inline trimming,trimBlocksandlstripBlocksenvironment options. - Custom delimiters: Configurable variable, block, and comment delimiters.
- Undefined variable behaviors: Silent (default), Strict, and Debug modes.
- Template caching: Content-hash-based caching with
sync.RWMutexprotection. - AST node pooling:
sync.Poolfor frequently allocated node types to reduce GC pressure. - Evaluator pooling: Reusable evaluators via
sync.Poolfor concurrent rendering. - Inheritance caching: Configurable TTL-based cache for resolved template hierarchies.
- Extension system: Custom tags and extensions via the
extensionspackage. - Error system: Enhanced errors with source context, suggestions, stack traces, and 9 error type categories.
- Template validation: Rule-based validator for common template mistakes.
- Template debugging: Breakpoints, variable watching, and step mode.
- Filesystem and memory loaders: Load templates from disk or in-memory maps.
- Concurrent rendering:
ConcurrentTemplateRendererwith worker pools and panic recovery. - Zero external dependencies: Built entirely on the Go standard library.