Upgrade Guide
Upgrading from v5 to v6 introduces some breaking changes: the loop object scope in nested loops, loop control directives crossing component boundaries, whitespace handling around standalone directives and comments, defined() returning false for missing properties and indices, HTML escaping of @insert and @reserve values and more.
If you installed Textwire from Codeberg (codeberg.org/textwire/textwire/v5), follow the Migrating from Codeberg guide first to move your imports back to GitHub, then continue here. If you stayed on GitHub the whole time, only the version suffix in your imports changes.
A lot of changes but it needs to be done while Textwire is still young. It's much harder to make these changes later when there are more users and more templates in the wild.
Most of these changes are not going to effect you but still you need to go through your templates and code to make sure everything works as expected. This guide will help you identify the changes that affect your project and how to fix them.
Breaking Changes
Relative loop Object in Nested Loops
In v5, the loop object inside a nested loop referred to the parent loop. In v6, loop is relative to the current loop. If you need metadata from the parent loop, use loop.parent.
For example, in v5 this printed the parent loop index:
@each(group in groups)
@each(item in group.items)
{{ loop.index }}
@end
@endIn v6, loop.index refers to the current inner loop. To keep the old behavior, use loop.parent.index:
@each(group in groups)
@each(item in group.items)
{{ loop.parent.index }}
@end
@endThis also applies to other loop properties such as loop.first, loop.last, and loop.iter. Non-nested loops are not affected. Closes #138.
Loop Control Directives Across Component Boundaries
In v5, using a loop control directive (@break, @continue, @breakif, or @continueif) inside a component body to control a loop outside that component was silently ignored. In v6, it results in a parser error.
Components are now a boundary for loop control, even though the component body can access variables from the surrounding scope.
@each(name in names)
@component('user')
@breakif(name == 'Skirk')
@end
@end
{{-- ERROR: @breakif is not allowed inside @component --}}A loop defined inside the component body can still use its own loop control directives.
Standalone Directive Whitespace
In v6, Textwire follows Mustache's standalone-tag whitespace rules. Only lines where exactly one directive or Textwire comment is the sole non-whitespace content are trimmed. Lines containing embedded expressions or other content keep their whitespace and line endings. This is different from v5, where all whitespace was preserved and some newlines were removed, which caused issues with whitespace-sensitive formats such as YAML.
In v5, removing a standalone comment left its indentation and line ending behind, producing a blank line. In v6, the whole comment line is removed.
See Whitespace Handling for details and examples.
defined() Returns false for Missing Properties and Indices
In v5, defined() returned true when you checked a property that didn't exist on an object or an index outside an array, because both evaluated to nil. In v6, both return false. A property or index that exists and holds nil still counts as defined.
{{ empty = {} }}
{{ defined(empty.name) }} {{-- v5: true, v6: false --}}
{{ withNil = { name: nil } }}
{{ defined(withNil.name) }} {{-- v5: true, v6: true --}}
{{ arr = [1, 2] }}
{{ defined(arr[5]) }} {{-- v5: true, v6: false --}}
{{ defined(arr[-1]) }} {{-- v5: true, v6: false --}}This also applies to chained access. defined(user.address.street.number) returns false if any part of the chain is missing.
Closes #167.
Component Depth Limit
In v6, components can be nested at most 500 levels deep during a single render. If a component includes itself, directly or through other components, Textwire stops with an error instead of crashing the program with a stack overflow. Components rendered one after another, like inside of a loop, don't count toward the limit.
This most likely doesn't affect you. But if you rely on recursive component calls and the depth goes higher than 500, change the MaxComponentDepth configuration. See Available Configurations for details.
Escaped @insert and @reserve Values
In v5, the short form @insert("title", value) and the @reserve("title", fallback) fallback printed their values raw. In v6, they are HTML-escaped the same way as {{ }}, which prevents XSS when user data is passed this way.
{{-- index.tw --}}
@use("layout")
@insert("title", "<span>Title</span>"){{-- layout.tw --}}
<title>@reserve("title")</title>In v5 the output was:
<title><span>Title</span></title>In v6 the same code produces:
<title><span>Title</span></title>If the HTML is trusted and should be printed as is, wrap the value in raw():
@insert("title", raw("<span>Title</span>"))For @insert, you can also use the block form, which is a normal template body:
@insert("title")
<span>Title</span>
@endDo not use raw() for user-provided data unless it was sanitized first.
Closes #156.
Read-Only Global Data
In v5, assigning to global, one of its properties, or a value aliased from it was silently ignored. In v6, it returns an evaluation error. This applies everywhere: templates, layouts, components, and loops.
{{ global.limit = 99 }} {{-- ERROR... --}}
{{ global.user.name = "Bob" }} {{-- ERROR... --}}
{{ global.tags[0] = "new" }} {{-- ERROR... --}}
{{ global.count++ }} {{-- ERROR... --}}
{{ user = global.user }}
{{ user.name = "Bob" }} {{-- ERROR... --}}Global data is meant to be read, not changed. If a template needs a modified value, create a new local value instead:
{{ user = { name: "Bob", role: global.user.role } }}Since v5 ignored these writes, you shouldn't have any code that depends on them. If you do, just remove those assignments since they are dead code anyway.
Global Data Converted Once at Template Creation
In v5, GlobalData was converted while rendering, so changes to the original map after NewTemplate were picked up. In v6, it is converted once inside NewTemplate and frozen, so later changes are not picked up:
global := map[string]any{"env": "dev"}
tpl, err := textwire.NewTemplate(&config.Config{GlobalData: global})
if err != nil {
// handle error
}
// v5: templates see "prod", v6: templates still see "dev"
global["env"] = "prod"Unsupported values, such as functions and channels, now fail in NewTemplate instead of at render time:
_, err := textwire.NewTemplate(&config.Config{
GlobalData: map[string]any{"callback": func() {}},
})
// v6: NewTemplate returns "unsupported value type 'func()'"Finish global data before calling NewTemplate. For values that change per render, pass them to String() or Response() as template data instead of mutating GlobalData.
Public pkg/ API Changes
If you import Textwire's pkg/ packages directly, three functions changed:
| v5 | v6 |
|---|---|
evaluator.New(customFunc, conf) | evaluator.New(customFunc, conf, global) |
value.NewScopeFromMap(data) | value.NewScopeFromMap(data, global) |
scope.AddGlobal(key, value) | Removed. Pass the value through GlobalData. |
global is a *value.Obj. Pass nil to keep the previous behavior.
Before (v5):
scope, err := value.NewScopeFromMap(data)
if err != nil {
// handle error
}
scope.AddGlobal("env", "dev")
e := evaluator.New(customFunc, conf)After (v6):
global, err := value.NewFrozenGlobal(map[string]any{"env": "dev"})
if err != nil {
// handle error
}
scope, err := value.NewScopeFromMap(data, global)
if err != nil {
// handle error
}
e := evaluator.New(customFunc, conf, global)NewTemplate does this for you, so this only affects code that uses pkg/evaluator or pkg/value directly.
New Features
loop Object in @for Loops
@for loops now provide a loop object with the following properties:
| Property | Type | Description |
|---|---|---|
index | int | Current index number starting from 0 |
iter | int | Current iteration number starting from 1 |
first | bool | Is the first iteration of the loop or not? |
parent | object | Parent loop object when loops are nested |
The last property is not available because a for loop may not have a known length. Accessing loop.last in a @for loop returns nil. See the loop object documentation for more information.
@for(i = 0; i < 5; i++)
<p>{{ loop.iter }} (index {{ loop.index }})</p>
@endCloses #130.
raw() Global Function
The new raw() global function marks a value as raw, so it is printed without HTML escaping. This is useful when you need unescaped output for a single value instead of a whole {!! !!} block. The function works recursively on strings in arrays and objects:
{{ raw("<span>Title</span>") }} {{-- Output: <span>Title</span> --}}
{{ raw(["<a>", "<b>"]) }} {{-- Output: <a>, <b> --}}
{{ raw({ name: "<b>" }) }} {{-- Output: {name: "<b>"} --}}See raw() for all details and examples.
Steps
1. Update Import Path
Replace all v5 imports with v6:
import "github.com/textwire/textwire/v5"
import "github.com/textwire/textwire/v5"After updating imports, run:
go mod tidy2. Update Nested Loops
If you access the parent loop object inside a nested loop, replace loop with loop.parent:
@each(group in groups)
@each(item in group.items)
{{ loop.index }}
{{ loop.parent.index }}
@end
@end3. Move Loop Control Directives Out of Components
If a loop control directive inside a component body targets a loop outside the component, move it into the surrounding loop, outside the @component call.
Before (v5):
@each(post in posts)
@component("components/post-card", { post })
@continue
@end
@endAfter (v6):
@each(post in posts)
@continue
@component("components/post-card", { post })@end
@end4. Review defined() Checks
Search your templates for defined() calls that check optional object properties or array indices. In v6 they return false when the property or index is missing:
@if(defined(user.address.street.number))
{{ user.address.street.number }}
@endIn v5 this block was entered even when user.address.street.number was missing, which hid mistakes. If a template depended on the old behavior, make the property exist with a nil value or guard the access with your own condition.
5. Check Whitespace-Sensitive Templates
Review templates where standalone directive or comment lines affect whitespace-sensitive output. In v6, only lines where exactly one directive or comment is the sole non-whitespace content are trimmed. See Whitespace Handling for details.
6. Review Escaped @insert and @reserve Values
Search your templates for the short form @insert("name", value) and @reserve("name", fallback). In v6, their values are HTML-escaped. If a value contained trusted HTML and should stay raw, wrap it in raw():
@insert("title", raw("<span>Title</span>"))
@reserve("title", raw("<i>Fallback</i>"))For @insert, you can also move static markup into the block form. Leave user-provided values escaped.
7. Review Recursive Components
Only needed if your components include each other recursively and go deeper than 500 levels. In that case, increase MaxComponentDepth in your Textwire configuration:
textwire.Configure(&config.Config{
MaxComponentDepth: 1000,
})See Available Configurations for details.
8. Remove Writes to Global Data
Search your templates for assignments, increments, or decrements that target global, its properties, array elements, or values aliased from it. In v6 they fail at render time. Since v5 ignored them, you can usually delete them. If a template needs the new value, use a local variable instead:
{{ global.theme = "dark" }}
{{ theme = "dark" }}An alias points to the same frozen value, so create a new local object when you need to modify a copy:
{{ user = global.user }}
{{ user.name = "Bob" }}
{{ user = { name: "Bob", role: global.user.role } }}9. Prepare Global Data Before NewTemplate
Move any changes to the GlobalData map before NewTemplate, and make sure it contains only supported values. Functions, channels, and other unsupported types now fail in NewTemplate:
tpl, err := textwire.NewTemplate(&config.Config{
GlobalData: map[string]any{"env": os.Getenv("APP_ENV")},
})
if err != nil {
// handle error
}Values that change per render should go through template data instead:
html, err := tpl.String("index", map[string]any{"user": user})10. Update Direct pkg/ Usage
Only needed if you call pkg/evaluator or pkg/value directly. Pass the global value to the constructors and remove Scope.AddGlobal calls:
scope, err := value.NewScopeFromMap(data)
scope, err := value.NewScopeFromMap(data, global)
e := evaluator.New(customFunc, conf)
e := evaluator.New(customFunc, conf, global)Pass nil for global to keep the previous behavior. See Public pkg/ API Changes for the full example.
Verification Checklist
After completing the migration:
Need Help?
- Check the Whitespace Handling page for whitespace rules
- Open an issue and we will help
- Read about defined() function
- Read about raw() function
