trellis 0.13.0
trellis: ^0.13.0 copied to clipboard
Template engine for Dart, using natural HTML templates. Fragment-first for hypermedia-driven frameworks like HTMX. Inspired by Thymeleaf.
Changelog #
0.13.0 #
Breaking #
tl:utextno longer processestl:*attributes in the HTML it inserts; they are output as-is, as Thymeleaf'sth:utextdoes. Processing them let any HTML that reachedtl:utextread every render-context value (<i tl:text="${secret}">) and include any template the loader can reach (tl:insert), which is server-side template injection, not only XSS. Markup that relied on it, such as rawtl:*HTML intrellis_siteMarkdown, now shows those attributes literally; move it into a template or shortcode.tl:utext="_"and an element wheretl:textwins keep their template content, which is still processed.- A
fragment:/fragments:value with arguments in parentheses (toast('error')) passed torenderFragment(),renderFragments()or their file variants now throwsTemplateExceptionnaming the bare name to pass instead, since parameters come from the render context. The value was matched against the literaltl:fragmentattribute, so passing a definition's full value (toast(type, title)) also throws now. An empty()(toast()) still resolves, as the bare name. - A same-file
tl:insert/tl:replaceby CSS selector (#id,.class) or tag name now copies the target as written in the template and processes the copy in the host's scope, as a by-name reference does. A target before the host was copied as already processed and then processed again, sotl:*attributes in HTML an earliertl:utextinserted were evaluated after all (template injection). The copy now evaluates its expressions with the host's variables instead of repeating the target's output, a target removed by its owntl:ifortl:removeis still found (and removes itself again), atl:eachtarget repeats inside the host instead of yielding its first rendered item, and anidorclassset bytl:id,tl:attrortl:classno longer matches. tl:inlineno longer evaluates text a custom processor creates: a newTextnode that replaces template text, or markup it builds from HTML it parses itself. To keep template text inlinable, set the existing node'sdata, with template text, never a value. This follows from thetl:inlinefix under Fixed.slotandattrsare now built-in attribute names. A custom dialect processor registered under either runs alongside the built-in handling, without an error; rename the custom attribute.FragmentHost.pushFragmentRegistrytakes an optional nameddocumentparameter, the file the registry came from. A class that implementsFragmentHostmust add it. This follows from the cross-file selector fix under Fixed.
Added #
- Content slots,
tl:slot(ADR-014). Inside atl:fragment, an element withtl:slot="name"declares a named region and a baretl:slotthe one anonymous region; its children are the fallback. At atl:insert/tl:replaceinvocation by fragment name, a literal direct child of the host withtl:slot="name"fills that region: the region element stays, its children are replaced, and the marker element is dropped, as withtl:define(<tl:block tl:slot="name">adds no wrapper). A filled region drops its owntl:text,tl:utext,tl:insertandtl:replace, so a region can default to a parameter (<button tl:slot="trigger" tl:text="${label}">) that the caller overrides. Several markers for one slot concatenate in document order, andtl:if/tl:unlesson a marker gate its contribution. Unmarked children (not whitespace-only text or comments) fill the anonymous slot when the fragment declares one and are discarded as before when it does not. Slot content is processed in the fragment's scope, so a region inside the fragment'stl:eachsees the loop variable. Markers nested deeper, including inside a plain<tl:block>, are not looked through; on a page they are inert. To forward a slot through a fragment that invokes another, re-mark it inside a direct-child marker (<tl:block tl:slot><p tl:slot="message">…</p></tl:block>). These throwTemplateExceptionat invocation: a marker naming a slot the fragment does not declare (including a bare marker without an anonymous slot, and any marker on a~{file :: #id}selector invocation), anothertl:*attribute on a marker, a duplicate slot name,tl:sloton thetl:fragmentelement itself, and, inside a definition, atl:slotwrapped in an inner host's unmarked content, which can neither fill the inner slot nor declare one (thrown even when the caller does not fill it or the inner invocation is gated off). Atl:slotoutside any fragment is stripped and its content kept. - Attribute spreading,
tl:attrs="${map}"(ADR-014). Writes each map entry as an attribute, before the element's other attribute directives (shorthands,tl:classappend/tl:styleappend,tl:attr), which override it. Entries overwrite literal attributes, exceptclassandstyle, which append. Values followtl:attr:nullremoves the attribute, and a boolean attribute (disabled,required, …) renders valueless fortrueand is removed forfalse. Anullmap is a no-op. A key differing from an existing attribute only in case replaces it, so aHREFkey cannot shadow an explicittl:href. A non-Mapvalue, a key that is not a valid HTML attribute name (empty, or containing whitespace, a control character,",',>,/,=or a noncharacter), or a key starting with the attribute prefix (tl:, case-insensitive, since it would run as a directive) throwsTemplateExceptionbefore any entry is written. - Attribute pass-through, the
...restfragment parameter (ADR-014). A fragment whose last parameter is...name(field(label, name, ...attrs)) (whitespace after...is ignored) receives under that name a map of the invoking host's attributes: its literal attributes plus the results of its own attribute directives (tl:attrs,tl:attr, shorthands, appends), evaluated once in the caller's scope, withouttl:*control attributes. Valueless attributes arrive as''and render valueless again. The fragment places the map withtl:attrs. Atl:inserthost keeps its directive results as well, so spreading the map repeats them there; components are invoked withtl:replace. A rest parameter named like a positional one (f(attrs, ...attrs)), or a repeated, non-final or unnamed one, throwsTemplateExceptionwhen the definition is collected, and so does an invocation with more positional arguments than the parameters before the rest parameter. Fragments without a rest parameter are unchanged: they ignore extra arguments, and atl:replacehost's attribute directives stay inert. - Top-level rendering of parameterised fragments.
renderFragment(),renderFragments(),renderFileFragment()andrenderFileFragments()find a fragment declared with parameters (toast(type, title)) by its bare name (fragment: 'toast'), as do the Shelf, Dart Frog and Relic helpers built on them. The parameters resolve from the same-named context keys like any variable (null when absent, a throw in strict mode), and a...restparameter is bound to an empty map. In strict mode, a parameter the fragment reads but the context lacks throwsExpressionExceptionnaming the fragment and the parameter (a missing parameter nothing reads renders fine). Previously only the literaltl:fragmentvalue matched, so a bare name threwFragmentNotFoundException. TemplateValidatorchecks for composition (alsodart run trellis:validate): atl:slotmarker under atl:insert/tl:replacehost that is not the host's literal direct child (a warning on a page, where it is inert; an error with the engine's message inside a fragment definition, unless it sits inside a direct-child marker), a repeated, non-final or unnamed...restparameter (error), and a literalidon or inside a parameterised fragment that neithertl:idnor atl:attridbinding overrides and the render keeps (warning, since the fragment can render several times on one page; skipstl:replaceelements,tl:remove="all", the children of atl:text/tl:utextelement that replaces them, and atl:replace/tl:inserthost's children except its direct-childtl:slotmarkers' content, which renders in the invoked fragment and is scanned; a host's unmarked children, which render only in an anonymous slot, stay unscanned).tl:slotandtl:attrscount as known attributes, and atl:attrsexpression is syntax-checked.
Fixed #
tl:inlinenow evaluates[[…]]/[(…)]only in template text, never in a text node a processor added: the output oftl:text,tl:utext, a custom processor or an earlier inline expression, on the same element or brought into atl:inserthost by the fragment. It ran after them, so a value such as[[${secret}]]read the render context (template injection). Template text is still inlined, including the text an element keeps withtl:text="_"ortl:utext="_"and a fragment's own text under atl:inlinehost. Text a custom processor creates is no longer inlined (see Breaking).tl:classappendandtl:styleappendtreat a blankclassorstyle(empty or whitespace) as absent, so<div class="" tl:classappend="a">rendersclass="a", notclass=" a".tl:attrsfollows the same rule.tl:attr, the shorthands (tl:href,tl:id, ...) andtl:classappend/tl:styleappendnow replace an attribute whose name differs only in ASCII case, and a namespaced foreign attribute such asxlink:hrefon SVG<use>, so the later write wins.<a id="lit" tl:attr="ID=${v}">renderedid="lit" ID="x"(browsers keep the first) and now renders one attribute. Boolean attributes are recognised ignoring case too ({'DISABLED': false}removesdisabled).- A self-closing
<tl:block … />in a fragment included from another file (~{file :: name}) no longer swallows the elements after it. Cross-file sources skipped the self-closing normalisation that same-file templates and the validator apply. - Inside a fragment included from another file (
~{file :: name}), atl:insert/tl:replacetarget by CSS selector (#id,.class) or tag name now resolves in that file first, as a by-name target already did, and falls back to the page only when the file has no match. It was looked up only in the page, so a component targeting its own#zthrewFragmentNotFoundException, or inserted a page element with the same id. Caller content filling a slot is processed in the fragment's scope, so its selector targets also try the fragment's file first, as its by-name targets do. - A processor with
autoProcessChildren => falsenow keeps the element's children unprocessed when a later-priority processor also fires on the element (tl:class,tl:attr,tl:remove, or a custom one). Only the last processor's flag counted, so the later one opted the children back in. tl:replacewith a fragment whose root is<tl:block>no longer leaves the<tl:block>tag in the output. It leaked inrender(),renderFragment(), insidetl:inserted fragments and intl:eachbodies, and an unknown inline element there collapses to 0×0 in the browser. The fragment clone was processed before it took the host's place, so every processor that acts on the root through its parent did nothing.tl:replacenow puts the clone in place first, which also fixes atl:if/tl:unlesson a replaced fragment's root (a false condition rendered the root anyway, rawtl:ifattribute included) and a roottl:each(threw a null-check error).tl:insertnow applies atl:if,tl:unless,tl:each,tl:removeortl:replaceon the fragment's root. It processed the root detached and moved only its children into the host, so a false condition ortl:remove="all"still inserted the children, unprocessed with their rawtl:*attributes, and a roottl:eachortl:replacethrew. The root now acts as a<tl:block>that is the host's only child: a removed root leaves the host empty, and a roottl:eachrepeats the children once per item inside the host.tl:remove="tag"now processes the children it keeps, anywhere, including on atl:inserted ortl:replaced fragment's root. It moved them out before the engine recursed into the element, so they were output raw with theirtl:*attributes (<b tl:text="${x}">). The element now unwraps after its children are processed, in its own context (atl:withon it applies), as<tl:block>does, so a later-priority processor on the element, a custom one atProcessorPriority.lowestincluded, now runs before it unwraps; attributes it sets go with the tag. HTML fromtl:utextortl:inserton the same element is still not processed again.renderFragment(),renderFragments()and their file variants now process the directives on the rendered fragment's own root as the fragment would be in place. The root was processed with no parent, so a roottl:replace(<div tl:fragment="w(x)" tl:replace="leaf(${x})">) threwUnsupportedError, a roottl:eachthrew a null-check error, and a roottl:ifthat is false,tl:unlessthat is true ortl:remove="all"returned the element with its rawtl:*attributes. The root now gets a temporary parent:tl:replacerenders the target,tl:eachone element per item (also for a parameterised root), a removed root renders nothing (renderFragments()concatenates the rest), andtl:remove="tag"or a<tl:block>root render their processed children.
0.12.0 #
Changed #
- Lockstep version bump to keep all Trellis SDK packages on a single shared version.
expectSnapshot,expectSnapshotFromSourceandcompareOrCreateGoldennow fail on a missing golden file when theCIenvironment variable istrue, instead of creating it and passing. On CI the created file was compared against itself and then discarded with the workspace, so a deleted or never-committed golden passed unnoticed. Local runs still create missing goldens on first run.compareOrCreateGoldentakes a newcreateMissingparameter to override the default.
0.11.1 #
Changed #
- Lockstep version bump to keep all Trellis SDK packages on a single shared version. No functional changes in this package.
0.11.0 #
Changed #
- Lockstep version bump to keep all Trellis SDK packages on a single shared version. No functional changes in this package.
0.10.2 #
Fixed #
- Dev-mode template watching now sees changes in nested template directories on Linux.
FileSystemLoader(devMode: true)relied onDirectory.watch(recursive: true), which dart:io implements with inotify on Linux — where therecursiveflag is silently ignored, so hot reload only ever noticed edits directly in the template root. On Linux the loader now watches each directory in the tree itself, adding watches for directories that appear later (including ones created or moved in already carrying templates) and dropping them when they go away; the per-directory walk tolerates unreadable directories, so one of them does not stop the rest of the tree from being watched. macOS and Windows keep the single native recursive watch. No API change. - A template updated by rename now triggers a reload on Linux and Windows. Atomic-save tools (
sed -i, rsync, some editors) writepage.html.tmpand rename it overpage.html; that arrives as a single move event whose path is the source, so the template-extension filter — which checked only that path — never fired. macOS reports renames as delete + create and was unaffected. - A template directory the OS refuses to watch — most often Linux's
fs.inotify.max_user_watcheslimit on a large template tree — now prints one warning naming the directory, instead of capping hot reload silently. (Per-directory watching, so Linux; macOS/Windows keep the native watch's existing error behaviour.) close()on a dev-modeFileSystemLoadercan no longer leave a watch behind: an event arriving while it was cancelling could install a new directory watch that the shutdown had already passed by.listTemplates()no longer follows symlinks, so every name it returns is oneload()will actually serve. It previously listed templates reached through a symlink out of the template tree, whichload()then rejected as a boundary escape — turning up as spuriouswarmUpAll()failures. A symlink pointing back inside the tree is also no longer listed: its target stays listed under the real path, andload()still serves the alias name, but the alias itself disappears from enumeration-driven features (warmUpAll(),trellis_dev's validator).
0.10.1 #
Breaking #
ProcessorContext.domProcessoris now typedFragmentHost(non-nullable) instead ofdynamic. This is a source break for code that constructsProcessorContextdirectly — anullor duck-typed stub that compiled against 0.10.0 no longer does. Shipped as a patch deliberately: Trellis is pre-1.0 with no known external users,ProcessorContextis documented as something aProcessorreceives (never constructs), andpackage:trellis/testing.dartis the supported test path. If you do construct one, pass aFragmentHostimplementation.
Added #
FragmentHost— the narrow fragment-resolution contract (evaluator,processFragmentContent,querySelectorFromDoc,lookupFragment,pushFragmentRegistry,popFragmentRegistry) implemented by the engine's DOM processor. Declaredabstract interface class, so future members can be added without breaking implementers.
Changed #
- Fragment-aware processors now get static checking on
context.domProcessorrather than unchecked dynamic dispatch; the internalas DomProcessorcast is gone.
0.10.0 #
Changed #
- Lockstep version bump to keep all Trellis SDK packages on a single shared version. No functional changes in this package.
0.9.1 #
Changed #
- Lockstep version bump to keep all Trellis SDK packages on a single shared version. No functional changes in this package.
0.9.0 #
Changed #
- Lockstep version bump to keep all Trellis SDK packages on a single shared version. No functional changes in this package.
All notable changes to trellis are documented here. This project follows Semantic Versioning.
0.8.2 #
Added #
trellis:validate --strictCI gate: the--strictflag (alias--fatal-warnings) makes the CLI exit1on warnings, not only errors. This letsdart run trellis:validategate CI on the silent HTML5-parser mutations surfaced in 0.8.1 (duplicatetl:attr,<table>/<select>foster-parenting) — these are reported as warnings, so a plain run exits0even when present.trellis:validateaccepts the target directory positionally —dart run trellis:validate templatesnow works alongside--dir templates.
0.8.1 #
Fixed #
TemplateValidatorsurfaces silent HTML5 parser mutations: templates are parsed bypackage:htmlbeforetl:*processors run, and the parser can silently rewrite malformed input – dropping duplicate attributes and foster-parenting elements out of<table>/<select>– strippingtl:*directives with no error. The validator now reports these as warnings:- Duplicate
tl:attron one element – only the first is kept (HTML forbids duplicate attribute names); use a single comma-separatedtl:attrinstead. tl:each/tl:*on a<tl:block>(or other unknown tag) inside<table>/<select>– foster-parented out of the table, detaching the loop scope; put the directive directly on<tr>/<option>.
- Duplicate
0.8.0 #
Added #
- Expression utility objects:
${#strings.*},${#numbers.*},${#dates.*},${#lists.*}— 53 built-in methods for common string, number, date, and list operations#strings:capitalize,upperCase,lowerCase,trim,isEmpty,isNotEmpty,length,contains,startsWith,endsWith,replace,substring,indexOf,split,join,repeat#numbers:formatDecimal,formatCurrency,formatPercent,abs,min,max,round,floor,ceil,isOdd,isEven#dates:format,formatDate,formatTime,now,year,month,day,hour,minute,second,isBefore,isAfter#lists:size,isEmpty,isNotEmpty,first,last,contains,sort,sortBy,reverse,take,skip,where,map,join,flatten
UtilityCallExprAST node and parser rule for${#name.method(args)}syntax#dates.formatand#numbers.formatusepackage:intlwhen available, English-only fallback otherwise- Unknown utility object or method produces
ExpressionExceptionwith a message listing available options - Testing utilities — merged
trellis_testinto core aspackage:trellis/testing.dart:testEngine()— preconfigured engine factory for testing withMapLoader, strict mode enabled, and caching disabled- CSS-selector HTML matchers:
hasElement,hasNoElement,hasAttribute,elementCount,hasTextContent - Snapshot golden file testing:
expectSnapshot,expectSnapshotFromSource— auto-creates on first run, fails with readable diff on mismatch;TRELLIS_UPDATE_GOLDENS=trueregenerates all golden files - Fragment isolation helpers:
testFragment,testFragmentFile normalizeHtml()— parse-and-serialize round-trip for stable snapshot comparison
Changed #
- Added
matcherdependency to support the mergedtesting.dartmatchers
0.7.0 #
Added #
- Template inheritance:
tl:extendsandtl:definefor layout-based template composition — child templates extend parents and override named blocks - Contextual escaping: URL-encoding for
@{}expressions,tl:href, andtl:srcattributes — values are properly percent-encoded for safe URL construction - Inheritance validation:
TemplateValidatorrecognizestl:extendsandtl:defineattributes, warns on duplicate block names, validates non-empty values
Changed #
InheritanceResolverruns as a pre-pass between DOM cloning and fragment collection — transparent to existing render pipelineloadSync()method onTemplateLoaderfor synchronous parent template loading (maintains sync-first contract ofrender())
0.6.0 #
Added #
- Expression AST cache: parsed expressions are now cached per
Trellisinstance and exposed viacacheStats.expressionCacheSize - Warm-up APIs:
warmUp()andwarmUpAll()pre-load templates into the DOM cache withWarmUpResultreporting for failures and evictions - Template discovery:
listTemplates()onFileSystemLoaderandMapLoaderfor startup warm-up workflows - Template validation toolkit:
TemplateValidator,ValidationError, andValidationSeverityfor static template checks - Testing helper:
package:trellis/testing.dartexportsisValidTemplate()for unit-test assertions - CLI validator:
dart run trellis:validatevalidates template directories for CI usage
0.5.0 #
Added #
devModeparameter onFileSystemLoader— file watching viadart:ioDirectory.watch()devModeparameter onTrellis— automatic cache invalidation on template file changesclose()onFileSystemLoaderandTrellisfor async resource disposalFileSystemLoader.changesstream for change notifications
0.4.1 #
- Added logo to README
0.4.0 #
- Bumped minimum Dart SDK from 3.7 to 3.10
- Applied Dart 3.10 dot shorthand syntax throughout
lib/src/(zero behavioral changes)
0.3.0 #
Added #
- Processor interface & pipeline:
Processorabstract class,ProcessorPriorityenum (8 priority slots),ProcessorContextclass — all built-in processors implement the interface; pipeline iterates a sorted processor list - Custom processor registration:
DomProcessor(processors: [...])registers customProcessorinstances with auto-prefixed attributes, priority-sorted merge, error wrapping, andautoProcessChildrencontrol - Dialect system:
Dialectabstract class andStandardDialect;DomProcessor(dialects: [...], includeStandard: false)composes processors and filters across multiple dialects - Filter arguments:
| filterName:arg1:arg2syntax for parameterized filters; supports string (\'escape), int, double, bool, null, and bare identifier args; backward compatible with existingFunction(dynamic)filters - i18n message expressions:
#{key}expression type withMessageSourceabstract class andMapMessageSourceimplementation; parameterized messages#{key(arg1, arg2)}with{0}/{1}positional replacement; locale support via engine config and_localecontext override; strict/lenient missing-key behavior AssetLoader: loads templates from Dart package assets viaIsolate.resolvePackageUriCompositeLoader: tries delegate loaders in order, falling back onTemplateNotFoundExceptionTrellisconstructor params:processors,dialects,includeStandard,messageSource,locale- Framework Integration Guide:
docs/guides/framework-integration.mdcovering shelf, dart_frog, and HTMX patterns - Todo app example:
example/todo_app/— full Shelf + HTMX app demonstrating v0.3 features
Changed #
example/restructured intoexample/basic/andexample/todo_app/sub-packages
0.2.1 #
Fixed #
tl:blockself-closing:<tl:block/>no longer swallows subsequent siblings — normalizer now uses a quote-aware scanner instead of a regex, correctly handling>inside attribute values (e.g.tl:if="${count > 0}")tl:fragmentontl:block:renderFragment()andrenderFragments()now correctly unwrap block elements, returning inner content instead of empty outputtl:eachwith null/missing iterable: gracefully removes the host element instead of throwing; consistent with lenient-mode semantics
Added #
!negation operator:!is now supported as an alias fornotin expressions (e.g.tl:if="!${active}")
0.2.0 #
Added #
- Expression enhancements: arithmetic operators (
+ - * / %), literal substitution (|Hello, ${name}!|), dynamic index expressions (${list[index]}), selection expressions (*{field}withtl:object), comparison aliases (gt,lt,ge,le,eq,ne), no-op token (_) tl:switch/tl:case: multi-branch conditional renderingtl:classappend/tl:styleappend: append to existing class/style attributestl:block: virtual element that renders only its children (no host element in output)tl:remove: remove elements or content from output (all,body,tag,all-but-first,none)tl:inline: inline expression processing in text, JavaScript, and CSS contexts ([[${expr}]]escaped,[(${expr})]unescaped)tl:object/*{}: object context and selection expressions for scoped field access; auto-conversion viatoMap()/toJson()- Parameterized fragments:
tl:fragment="card(title, body)"with argument passing at inclusion time - CSS selector targeting:
tl:insert="~{file :: #id}"andtl:insert="~{file :: .class}" - Cycle detection: fragment inclusion stack replaces depth-only guard — recursive inclusions detected immediately
renderFragments(): render multiple named fragments from a single template string in one callrenderFileFragments(): async variant loading from the filesystem- Strict mode:
Trellis(strict: true)— undefined variables, members, and keys throwExpressionException - LRU cache: configurable max cache size via
maxCacheSizeparameter; evicts least-recently-used entries CacheStats: expose cache hit/miss/size metrics viaengine.cacheStatsclearCache(): clear DOM cache and reset statisticsTrellisContext: fluent builder for constructing rendering context mapsdata-tl-*prefix mode:Trellis(prefix: 'data-tl')for strict HTML5-valid attribute names
Fixed #
- Expression parser: alias/keyword words (
gt,eq,and,true, etc.) now work as member names after.— e.g.${obj.eq},${stats.gt} - README: corrected
TrellisContextexample,renderFragmentsreturn types,tl:switchcase syntax,tl:classappendternary,maxCacheSizedefault, removed nonexistentseparatorparameter
Changed #
- Fragment registry entries now carry parameter names for parameterized fragment resolution
- Inclusion depth guard replaced by cycle detection stack (still enforces max depth 32 as hard limit)
0.1.0 #
Added #
- Core template engine with 15
tl:*attributes for natural HTML templating - Text substitution:
tl:text(escaped) andtl:utext(unescaped HTML) - Conditionals:
tl:ifandtl:unless - Iteration:
tl:eachwith status variables (index, count, size, first, last, odd, even, current) - Fragment system:
tl:fragment,tl:insert,tl:replacewith cross-file inclusion - Local variable binding:
tl:with - Attribute setting:
tl:attr,tl:href,tl:src,tl:value,tl:class,tl:id - Expression evaluator:
${var}variables,@{/url}URL expressions, string literals, ternary, Elvis, comparisons, boolean operators - Four public API methods:
render(),renderFile(),renderFragment(),renderFileFragment() - DOM caching with deep-clone for performance
- Configurable attribute prefix (default
tl) FileSystemLoaderwith security boundary enforcement (path traversal, symlink escape protection)MapLoaderfor in-memory templates and testing- Typed exception hierarchy:
TemplateException,ExpressionException,FragmentNotFoundException,TemplateNotFoundException,TemplateSecurityException