Cascada Template Documentation
Cascada is in active development. APIs and syntax may change. Feedback and contributions are welcome.
Reference Documentation:
- CascadaScript Documentation - Complete reference for CascadaScript features
- Nunjucks Templating Documentation - Nunjucks syntax and features
This document focuses on the differences between CascadaScript and Cascada Template syntax. For complete coverage of features, consult the reference documentation above.
Cascada Templates provide an alternative syntax for writing Cascada workflows using a template-based approach similar to Nunjucks/Jinja2. While CascadaScript is optimized for data orchestration with explicit channel declarations, Cascada Templates are ideal for text generation with embedded logic.
Async template loops share replayable external async iterables. Every loop sees the full sequence; early termination requires explicit source disposal.
Cascada maintains full compatibility with Nunjucks when running in non-async mode.
Template vs Script: Key Differences
Cascada Templates are built on top of Nunjucks and support most CascadaScript control-flow and expression features, but with these key differences:
- Text output is the default - Content outside tags renders as text; in scripts, use a
textchannel to build text output explicitly - Expressions in
{{ }}- Use double braces for value interpolation - No channels -
dataandtextchannel declarations are script-only; templates output text implicitly - No
sequencedeclarations -sequence name = valueis script-only and is not supported in templates. Use!on static context paths for ordered external interactions. - Tags use
{% %}- All logic goes inside tag delimiters (use standard Nunjucks whitespace control where needed) setfor variables and assignment - Use Nunjucks{% set %}syntax instead of Script'svarand=dofor execution-only expressions - Standalone calls and sequential path repair (!!) use{% do %}- Script is stricter about scalar misuse - Scripts poison property access on scalar primitives and loops over scalar primitives; templates keep Nunjucks-style leniency (
undefined/ loopelse) - Script operators are stricter - Scripts use strict
==/!=and typed numeric/order operands; templates keep Nunjucks-style loose equality and JavaScript coercion. Invalidinoperands poison in both modes.
Render vs Return: The Core Difference
Scripts return values; templates render text. This applies uniformly to every callable construct:
| CascadaScript | Cascada Template | |
|---|---|---|
| Overall result | Explicit return value or return ch.snapshot() |
Text accumulated in the output stream |
| Function / macro | Returns a value - var result = fn(args) |
Renders text inline - {{ macro(args) }} |
| Call block body | Must return explicitly; outer form is var x = call fn() |
Renders text; no explicit return |
caller() |
Returns the call block body's return value |
Renders the call block body's text inline |
| Method / block | Returns a value via return |
Renders text inline |
super() |
Returns the parent method's value | Renders the parent block's text |
Examples
Script Example
var user = fetchUser(userId)
var posts = fetchPosts(user.id)
text output
output("# User Profile\n\n")
output("Name: " + user.name + "\n")
output("Posts:\n")
for post in posts
output("- " + post.title + "\n")
endfor
return output.snapshot()
Equivalent Template
{% set user = fetchUser(userId) %}
{% set posts = fetchPosts(user.id) %}
# User Profile
Name: {{ user.name }}
Posts:
{% for post in posts %}
- {{ post.title }}
{% endfor %}
The do Tag
The {% do %} tag executes expressions without rendering any output. In Script mode, the equivalent is simply writing the expression on its own line.
Sequential Path Repair (!!)
The sequential path repair operator !! repairs poisoned ! paths. In templates, it must be used with {% do %}. A path must first be established with ! before it can be checked or repaired:
{% do api!.connect() %}
{% if api! is error %}
{% do api!! %}
{% endif %}
Script and Template Syntax Reference
| Feature | CascadaScript | Cascada Template |
|---|---|---|
| Text channel | text t |
(text output is implicit - no declaration needed) |
| Text channel write | t("Hello " + user.name) |
Hello {{ user.name }} |
| Expressions | t(total * 1.2) |
{{ total * 1.2 }} |
| Variable Declaration | var user = fetchUser(1) |
{% set user = fetchUser(1) %} |
| Assignment | count = count + 1 |
{% set count = count + 1 %} |
| Multiple Variables | var x, y = none |
{% set x, y = none %} |
| Comments | // Single line/* Multi line */ |
{# Single or multi-line #} |
| Filters | t(name | upper) |
{{ name | upper }} |
| Filter with Args | t(items | join(", ")) |
{{ items | join(", ") }} |
| Execution-only Call | service.notify(user) |
{% do service.notify(user) %} |
| Sequential Path Repair | api!! |
{% do api!! %} |
| If Statement | if user.age >= 18...elif ......else...endif |
{% if user.age >= 18 %}...{% elseif ... %} or {% elif ... %}...{% else %}...{% endif %} |
| For Loop | for item in items...endfor |
{% for item in items %}...{% endfor %} |
| Each Loop | each item in items...endeach |
{% asyncEach item in items %}...{% endeach %} |
| While Loop | while count < 10...endwhile |
{% while count < 10 %}...{% endwhile %} |
| Switch | switch valuecase 1...endswitch |
{% switch value %}{% case 1 %}...{% endswitch %} |
| Function Definition | function greet(name)...endfunction |
{% macro greet(name) %}...{% endmacro %} |
| Function/Macro Calls | var result = greet("Alice") |
{{ greet("Alice") }} |
| Call Block | var x = call wrapper()(param)return valueendcall |
{% call wrapper() %}...{% endcall %} |
| Caller Invocation | var result = caller(value) |
{{ caller() }} |
| Block Assignment | (not available in scripts) | {% set html %}...{% endset %} |
| Template Inheritance | extends "base.html" |
{% extends "base.html" %} |
| Inherited Override | method name(arg1, arg2)...endmethod |
{% block name(arg1, arg2) %}...{% endblock %} |
| Shared var declaration | shared var theme = "dark" |
(inferred automatically - no declaration needed) |
| Shared var write | this.theme = "dark" |
{% set this.theme = "dark" %} |
| Shared var read | this.theme |
{{ this.theme }} |
| Nested shared var read | this.user.name |
{{ this.user.name }} |
| Include | (not supported in scripts) | {% include "file" %} |
| Include with inputs | (not supported in scripts) | {% include "file" with context, var1, var2 %} |
| Import namespace | import "file" as lib |
{% import "file" as lib %} |
| Import with inputs | import "file" as lib with context, var1 |
{% import "file" as lib with context, var1 %} |
| Import with object | import "file" as lib with { key: expr } |
{% import "file" as lib with { key: expr } %} |
| Import names | from "file" import helper |
{% from "file" import helper %} |
| From import with inputs | from "file" import helper with context, var1 |
{% from "file" import helper with context, var1 %} |
| Guard Block | guard...recover...endguard |
{% guard %}...{% recover %}...{% endguard %} |
Macros
A template macro renders text where it is called. This differs from CascadaScript functions, which return values:
{% macro button(label) %}
<button>{{ label }}</button>
{% endmacro %}
{{ button("Save") }}
Cascada async templates are stricter than classic Nunjucks/sync templates: local macro names are call-only and cannot be used as ordinary values. A macro call can still be used inside an expression; it contributes its rendered string:
{{ button("Save") }}
{{ button("Save") ~ "!" }}
{{ button }} {# error #}
{{ helper(button) }} {# error #}
{% set x = button %} {# error: button is read as a value #}
Imported names can be Cascada macros or ordinary functions. In async templates an imported name is used either for calls or as an ordinary value, not both; for namespace imports this applies per member:
{% from "ui.njk" import button %}
{{ button("Save") }}
{{ button }} {# error #}
{% import "ui.njk" as ui %}
{{ ui.button("Save") }}
{{ ui.button }} {# error #}
{{ ui.version }} {# valid ordinary namespace member #}
Macros and inherited blocks can call imported paths that were imported earlier in the same template. with context imports work from inside macros and blocks; imports with explicit inputs, object inputs, or dynamic targets must be called from ordinary root code instead.
This lets Cascada preserve deterministic output ordering and parallel execution without tracing macro values through variables. CascadaScript is not subject to this template call-only rule; script functions return values and can be assigned to local variables and called through them.
Call Blocks and caller()
In scripts, call blocks must always use assignment form:
function map(items)
data results
for item in items
var result = caller(item) // receives the call block's return value
results.items.push(result)
endfor
return results.snapshot()
endfunction
var mapped = call map([1, 2, 3])
(n)
return n * n // explicit return - this is what caller() receives
endcall
// assignment form (only form supported in scripts):
var x = call wrapper(args)
(param)
return value
endcall
guard and recover
guard and recover work the same as in scripts. In templates, the relevant effect is that text output from the guarded scope is discarded if the guard fails (rather than restoring channel state, which is the script use case).
Manual revert
Manual revert is not available yet in async templates. Use ordinary error flow inside a guard: if the guarded block remains poisoned, Cascada discards its output and runs recover.
{% guard %}
{% set result = riskyCall() %}
Result: {{ result }}
{% recover %}
Could not load result.
{% endguard %}
Async Composition (with Payloads and Inheritance Contracts)
The full composition model - with, with context, resolution order, and pass-through patterns - is documented in Composition and Loading in the script docs. The same rules apply to templates; only the syntax differs. extends is not a composition boundary and does not accept with clauses.
Template-specific notes:
includeis supported in templates (it is not available in scripts). It follows the same isolation andwithrules asimport.- Templates do not support
component. To render another template, including an inherited template, useinclude; each include render gets its own inheritance state. - Template inheritance uses
{% block name(args) %}/{% endblock %}where scripts usemethod name(args)/endmethod. Both supportthis.blockName(args)/this.methodName(args)for calling an override via inherited dispatch. withclauses and the explicit payload model are async-only. In classic Nunjucks (sync) mode, templates retain implicit access to all parent-scope variables.
Async Template Inheritance
In template inheritance, the root or base template describes the structure of the document. Its text and block positions decide where output appears. A child template customizes that structure by overriding named blocks; the override fills the parent block position rather than rendering where the child wrote the override.
Code outside blocks is constructor code. It can write shared state through
this.<name> and may contain ordinary template control flow. A template with
extends uses its blocks as overrides. A template without extends can place
its blocks directly in the output.
The extends target is resolved before constructor code runs, so it may read
render-context values and globals but not values created by top-level
{% set %} in the same template or inferred shared vars such as
this.theme. Templates do not support extends none, extends ... with ...,
or dynamic-null parent selection. If a template has extends, it must select
a parent template. Nothing except whitespace and comments may appear before
{% extends %}.
Template constructor code reaches the parent constructor through an implicit
trailing super() when a parent is selected. Block bodies may also use
super() to render the parent block.
Classic Nunjucks blocks have implicit access to the caller's local scope.
Cascada async blocks are more explicit: they can read render-context names by
default, but they do not capture surrounding template locals such as loop
variables, branch locals, or values created with {% set %}. Pass those
placement-local values as block arguments:
{# Nunjucks - block sees caller's local variables implicitly #}
{% set user = getUser() %}
{% block greeting %}
Hello {{ user.name }}
{% endblock %}
{# Cascada async - placement-local values are passed explicitly #}
{% set user = getUser() %}
{% block greeting(user) %}
Hello {{ user.name }}
{% endblock %}
{% set accountUser = getUser() %}
{% block greeting(user = accountUser) %}
Hello {{ user.name }}
{% endblock %}
{% block name(arg1, arg2) %}- positional placement values, passed into block-local arguments with the same names.{% block name(arg = localValue) %}- named placement binding, passinglocalValueinto the block argument namedarg.- An override may have fewer block arguments than the parent, but any kept argument must use the same name. Named placement bindings (
arg = value) depend on stable argument names. super()renders the parent block with no arguments. Pass values explicitly, such assuper(user), when the parent block needs them.- Bare variables from the surrounding template local scope are not captured by a block. Pass loop/top-level values as block arguments, use render-context names, or read hierarchy state explicitly through
this.<name>.
Inheritance Example
{# base.njk #}
{% block content(user) %}
Base {{ user }} / {{ siteName }} / {{ theme or "light" }}
{% endblock %}
{# child.njk #}
{% extends "base.njk" %}
{% block content(user) %}
Child {{ user }} / {{ siteName }} / {{ super(user) }}
{% endblock %}
Rendered with:
{ user: "Ada", siteName: "Docs", theme: "dark" }
Produces:
Child Grace / Docs / Base Ada / Docs / dark
What this shows:
super(user)passes the child's currentuservalue to the parent block explicitly.siteNameis visible inside both blocks because render-context names are available by default.themecomes from the render context, which is visible throughout the selected inheritance chain by default.- A child top-level
{% set theme = ... %}would not be visible incontentby itself, and cannot be used by theextendstarget because parent selection happens before constructor code runs.
Shared State in Inherited Templates
In async templates, the this.<name> surface provides shared var state across an inheritance hierarchy - the template equivalent of shared var in scripts.
Key differences from scripts:
- No
shareddeclarations are needed. The compiler infers shared vars from staticthis.<name>paths in the template source. - Explicit
shareddeclarations are script-only. In templates,{% shared var theme %}is rejected; use{% set this.theme = ... %}and{{ this.theme }}instead. - Templates infer ordinary
this.<name>roots as sharedvarvalues, so no declaration is needed. The reservedthis.__text__root is the inherited template text channel and is the only typed shared-channel exception on this template surface. - Static
this.<name>paths use the inheritance surface even when the template does not containextendsorblock; use ordinary context names for plain render data. - Dynamic
this[expression]is not supported in inheritance templates.
{# base.njk #}
{% block body %}
Theme: {{ this.theme }}
{% endblock %}
{# child.njk #}
{% extends "base.njk" %}
{% set this.theme = "dark" %}
The child's {% set this.theme = "dark" %} writes the shared var explicitly through the inheritance state. The base's {{ this.theme }} inside the block reads it. Both templates infer theme automatically - no declaration required in either file.
Template shared-var writes are ordinary runtime assignments, not shared-default
initializers. In an extending template, top-level code runs before the implicit
parent super(), so a parent constructor assignment can overwrite a child
assignment. Use script shared var declarations for shared defaults; template
inference only provides the shared var channel.
Variable Scoping
Identifier names may contain letters, digits, and _, and must not contain $. The $ character is reserved for compiler-generated internal names.
Cascada templates do not allow shadowing of visible local names. This applies to {% for %} / {% each %} targets, call-block parameters, import namespaces, from ... import names, and block arguments - these always introduce a fresh binding. {% set %} is exempt: reusing a visible name reassigns it instead of declaring a new one, so it never shadows. Macros have their own local scope, so their parameters may reuse names from outside the macro:
{% set item = "outer" %}
{% macro render(item) %}
{{ item }} {# OK: macro parameters are local to the macro #}
{% endmacro %}
Concurrency Isolation
In async mode, every construct that can run concurrently gets its own isolated scope, preventing race conditions between concurrent branches or iterations:
| Construct | Classic Nunjucks / sync | Async Cascada Template |
|---|---|---|
if / switch |
No scope - {% set %} writes to parent |
Local scope - variables stay inside the branch |
for / each loop body |
All iterations share one inner scope that is discarded after the loop | Each iteration has its own isolated scope |
while loop body |
Uses the parent scope directly - {% set %} inside writes to the outer scope |
Each iteration has its own isolated scope |
Composition Isolation
All composition boundaries are isolated in async mode - the child sees only what is explicitly passed in, not the caller's local variables:
| Construct | Classic Nunjucks / sync | Async Cascada Template |
|---|---|---|
include |
Sees all caller's {% set %} variables |
Isolated - sees only explicit with inputs |
import |
Macros see only their own arguments | Isolated - sees only explicit with inputs |
block |
Sees caller's frame | Sees render-context names and declared block arguments; does not see caller/placement locals |
Child top-level {% set %} |
Visible in the child's own blocks | Not captured by blocks; pass it as a block arg or use this.<name> shared state |
Passing Data with with
All Cascada composition operations support with for passing data across isolation boundaries - the same syntax as in scripts, and unlike classic Nunjucks which has no equivalent. See with: Composition Payload in the script docs for the full rules.
Unresolved Names
In templates, a bare name that is neither declared nor found in the context becomes undefined (standard Nunjucks behavior - renders as empty).
In scripts, the same lookup becomes poison and will cause the script to fail if consumed or returned.
Unsupported Features
Script features not available in templates
- Channels:
dataandtextchannel declarations are script-only - Sequence declarations:
sequence name = valueis a separate script-only feature and is not supported in templates. In templates, use!on static context paths for ordered external interactions. - Property assignment:
obj.prop = valueis not supported; use{% set obj = ... %}to reassign entire variables
Template features not available in scripts
- Implicit text output: scripts have no implicit text rendering; use a
textchannel and returnt.snapshot() - Block assignment (
{% set var %}...{% endset %}): not available in scripts; use atextchannel instead. Note:{% set this.name = value %}is distinct - it writes to the hierarchy's shared varname, not a block-captured text value. {{ }}interpolation and{% %}tags: script syntax uses no delimiters
When to Use Templates vs Script
Use Cascada Templates when:
- Primary goal is text/HTML generation
- Rendered text is predominantly static with dynamic insertions
- Working with existing Nunjucks templates
Use CascadaScript when:
- Building structured data (JSON objects/arrays)
- Complex data orchestration workflows
- Need explicit control over multiple output streams
- Working with LLM orchestration or data pipelines
API Notes
Cascada keeps Nunjucks-compatible API names where useful, but new code should use the cascada-engine package name and Cascada class/function names. See the CascadaScript API section for the canonical API surface.
ESM And Browser Usage
Prefer ESM imports in Node and modern browser builds. The main entry can compile from source:
import { AsyncEnvironment, FileSystemLoader } from 'cascada-engine';
const env = new AsyncEnvironment(new FileSystemLoader('templates'));
const html = await env.renderTemplate('page.njk', data);
Use the precompiled entry when templates or scripts are compiled ahead of time and the app only needs the runtime. This entry does not import the compiler, parser, lexer, or precompile API:
import { AsyncEnvironment as PrecompiledEnvironment, PrecompiledLoader } from 'cascada-engine/precompiled';
Old Nunjucks-style UMD bundles and automatic window.nunjucks globals are not supported by the ESM package. Use ESM imports in browser code.