Language Reference
Marko is a superset of well-formed HTML. It enforces strict tag structure while extending HTML with JavaScript expressions, control flow, and compiled reactivity.
Syntax Legend
import "...";
<tag|...params|/var ...attrs>
content with ${placeholders}
<@attr-tag/>
</>import "...";
tag|...params|/var ...attrs
-- content with ${placeholders}
@attr-tagClick any part of the legend to jump to its section. Also see <${dynamic}/> tags, Attributes, Tag Arguments, and Concise Syntax.
Template Variables
Three variables are automatically available inside every template body.
input
A JavaScript object holding the attributes passed to a custom tag, or the data passed to the Template API.
$signal
An AbortSignal available inside template expressions, event handlers, and effect blocks (not in module-level statements). $signal exists only in the browser and is used to clean up side effects.
It aborts when:
- Any reactive value (tag variable, tag parameter, or
input) read by the expression or effect using$signalchanges, including reads inside callbacks it registers - The template or tag content is removed from the DOM
$signal is browser-only. Reading it during a server render (such as in an attribute, <const>, or interpolation) is invalid:
// ❌ Invalid during a server render
<const/results=fetch("/api/search", { signal: $signal })>// ❌ Invalid during a server render
const/results=fetch("/api/search", { signal: $signal })Use $signal only in browser-only contexts: <script> bodies, <lifecycle> hooks, and event handlers.
Pass $signal directly to web APIs such as addEventListener() for automatic cleanup. To register a run-once listener whose callback reads reactive state without re-registering on every change, use <lifecycle>.
<script>
window.addEventListener("resize", () => {
// automatically removed when the signal aborts
}, { signal: $signal });
</script>script
--
window.addEventListener("resize", () => {
// automatically removed when the signal aborts
}, { signal: $signal });
--$global
Provides access to the render globals passed to the Template API.
Statements
Marko supports module-scoped statements at the root of a template. These run once when the template module loads rather than on every render.
import
Standard JavaScript import statements are valid at the template root and are shorthand for static import.
import sum from "sum";
<div data-number=sum(1, 2)/>import sum from "sum";
div data-number=sum(1, 2)Tag import Shorthand
Angle brackets in the from specifier resolve a custom tag using Marko's tag discovery rules:
import MyTag from "<my-tag>";
<MyTag/>import MyTag from "<my-tag>";
MyTagLazy Tag import
Adding a load import attribute splits the tag into a separate browser bundle loaded on demand:
import HeavyChart from "<heavy-chart>" with { load: "visible#chart" };
<div#chart>
<HeavyChart data=input.data/>
</div>import HeavyChart from "<heavy-chart>" with { load: "visible#chart" };
div#chart
HeavyChart data=input.dataSee Lazy Loading for triggers and constraints.
export
Named JavaScript export statements are valid at the template root. The default export is reserved for the template itself.
export function getAnswer() {
return 42;
}
<div>${getAnswer()}</div>export function getAnswer() {
return 42;
}
div -- ${getAnswer()}static
Statements prefixed with static execute in module scope when the template loads on both server and browser. Any valid JavaScript statement, declaration, or block is supported (a static { ... } block unwraps its top-level bindings into module scope):
static const answer = 41;
static function getAnswer() {
return answer + 1;
}
<div data-answer=getAnswer()/>static const answer = 41;
static function getAnswer() {
return answer + 1;
}
div data-answer=getAnswer()static {
console.log("Logged once when the module loads");
}static {
console.log("Logged once when the module loads");
}server and client
Statements prefixed with server or client execute in module scope only in that target environment. Bindings declared in one environment evaluate to undefined in the other.
server console.log("on the server");
client console.log("in the browser");server console.log("on the server");
client console.log("in the browser");Environment prefixes also combine with import statements and blocks:
server import { connectToDatabase } from "./database";
client import "bootstrap";
server {
const db = connectToDatabase();
const users = await db.query("SELECT * FROM users");
console.log(`Found ${users.length} users`);
}server import { connectToDatabase } from "./database";
client import "bootstrap";
server {
const db = connectToDatabase();
const users = await db.query("SELECT * FROM users");
console.log(`Found ${users.length} users`);
}Attributes
Attribute values are JavaScript expressions, including quoted strings (str="Hello" is a JavaScript string literal, not an HTML attribute string):
<my-tag str="Hello"/>
<my-tag str=`Hello ${name}`/>
<my-tag num=1 + 1/>
<my-tag date=new Date()/>
<my-tag fn=function myFn(param1) { console.log("hi") }/>my-tag str="Hello"
my-tag str=`Hello ${name}`
my-tag num=1 + 1
my-tag date=new Date()
my-tag fn=function myFn(param1) { console.log("hi") }Dynamic native attribute values are encoded for HTML attribute syntax (escaping the active quote character, \r, and & when it would begin a character reference).
Attribute encoding protects HTML syntax only. URL-valued attributes such as href and src are written as given, so check untrusted URLs against an allowlist of schemes (excluding javascript:, data:, and unexpected protocol-relative // URLs).
Unenclosed > is ambiguous with the end of a tag, so wrap comparisons with > in parentheses. Whitespace-preceded >= and arrow functions (=>) need no parentheses:
<my-tag value=(1 > 2)/>
<my-tag value=count >= 10/>
<my-tag fn=x => x * 2/>my-tag value=(1 > 2)
my-tag value=count >= 10
my-tag fn=x => x * 2Skipped Attributes
Attributes whose value is null, undefined, or false are omitted from the HTML output. Other falsy values (0, 0n, NaN, and "") are still written, except empty class="" and style="", which are omitted. Dynamic text uses different skip rules.
Boolean Attributes
A valueless attribute evaluates to true. On native tags, true emits the attribute name with no value:
<input type="checkbox" checked>
<input type="checkbox" checked=true>input type="checkbox" checked
input type="checkbox" checked=trueARIA enumerated attributes expect explicit string values ("true" / "false"), not HTML boolean attributes:
// ❌ emits `<button aria-pressed></button>`
<button aria-pressed=isPressed/>
// ✅ emits `<button aria-pressed=true></button>` or `"false"`
<button aria-pressed=String(isPressed)/>// ❌ emits `<button aria-pressed></button>`
button aria-pressed=isPressed
// ✅ emits `<button aria-pressed=true></button>` or `"false"`
button aria-pressed=String(isPressed)Spread Attributes
Spread syntax applies an object of attributes to a tag:
<my-tag ...input foo="bar"/>my-tag ...input foo="bar"Attributes merge from left to right, with later attributes overriding earlier ones. The spread target can be any JavaScript expression, including an object literal shorthand:
<my-tag ...{ property }/>my-tag ...{ property }On native tags, a spread also manages removal of attributes dropped on subsequent updates.
Shorthand Methods
Method definitions pass functions concisely as attributes:
<button onClick(e) { console.log(e.target) }>Click Me</button>button onClick(e) { console.log(e.target) } -- Click MeNative tag event handlers also receive the attached element as a second parameter. Prefix the method with async to use await inside its body:
<button async onClick() { await save() }>Save</button>button async onClick() { await save() } -- SaveShorthand Change Handlers (Two-Way Binding)
attr:=x is optional shorthand for passing both attr= and attrChange=. Its right-hand side must be a tag variable, a destructured object property, or a property accessor (including optional input.a?.b and computed obj[key] access).
For a mutable tag variable, := desugars to an assignment handler:
<counter value:=count/>
// desugars to
<counter value=count valueChange(newCount) { count = newCount }/>counter value:=count
// desugars to
counter value=count valueChange(newCount) { count = newCount }For a property accessor (or a destructured object property such as <const/{ count }=input>), := forwards the corresponding *Change property:
<counter value:=input.count/>
// desugars to
<counter value=input.count valueChange=input.countChange/>counter value:=input.count
// desugars to
counter value=input.count valueChange=input.countChangeRefining Function
Insert :fn:= to transform values before passing them to the change handler:
<input type="number" value:parseFloat:=num>
// desugars to
<input
type="number"
value=num
valueChange(newValue) { num = parseFloat(newValue) }
>input type="number" value:parseFloat:=num
// desugars to
input
,type="number"
,value=num
,valueChange(newValue) { num = parseFloat(newValue) }For property accessors, the generated handler only runs when the upstream change handler is defined:
<input type="number" value:parseFloat:=input.num>
// desugars to
<input
type="number"
value=input.num
valueChange=(input.numChange && ((newValue) => {
input.numChange(parseFloat(newValue));
}))
>input type="number" value:parseFloat:=input.num
// desugars to
input
,type="number"
,value=input.num
,valueChange=(input.numChange && ((newValue) => {
input.numChange(parseFloat(newValue));
}))Shorthand class and id
Emmet-style #id and .class shorthands attach directly to a tag name. Omitting the tag name defaults to div, and shorthand classes merge with any class= attribute.
<div#foo.bar.baz/>
// same as
<div id="foo" class="bar baz"/>Interpolations work inside shorthand id and class names:
<div.icon-${iconName}/>Shorthand value
Omitting the attribute name at the start of a tag passes the value as value=:
<my-tag=1/>
// desugars to
<my-tag value=1/>my-tag=1
// desugars to
my-tag value=1Combining this with method shorthand passes a value function:
<my-tag() {
console.log("Hello JavaScript!");
}/>
// desugars to
<my-tag value=function () {
console.log("Hello JavaScript!");
}/>my-tag() {
console.log("Hello JavaScript!");
}
// desugars to
my-tag value=function () {
console.log("Hello JavaScript!");
}Attribute Termination
Attributes may be separated with commas, which is primarily used for multiline attributes in concise syntax:
<my-tag a=1 b=2/>my-tag a=1 b=2Wrap JavaScript comma expressions in parentheses so the comma is not parsed as an attribute separator:
<my-tag a=(console.log(foo), foo)/>my-tag a=(console.log(foo), foo)Tag Content
Markup inside a tag's body is passed to the tag as input.content. Custom tags render it with a dynamic tag:
<div class="card">
<${input.content}/>
</div>export interface Input {
content: Marko.Body;
}
<div class="card">
<${input.content}/>
</div>div class="card"
${input.content}export interface Input {
content: Marko.Body;
}
div class="card"
${input.content}<card>Content</card>card -- ContentNative tags also accept content= as an attribute, so the wrapper above can be written:
<div class="card" content=input.content/>div class="card" content=input.contentDynamic Text
Interpolate JavaScript expressions inside tag content with ${expression}, matching JavaScript template literals:
<div>Hello ${input.name}</div>export interface Input {
name: string;
}
<div>Hello ${input.name}</div>div -- Hello ${input.name}export interface Input {
name: string;
}
div -- Hello ${input.name}Static text in markup is emitted verbatim (preserving HTML character references). Dynamic ${...} text escapes <, &, and \r to <, &, and
to prevent XSS.
Skipped Values
Interpolated null, undefined, false, "", NaN, and 0n render nothing. All other values convert via string concatenation (0 renders 0, true renders true, arrays join with commas). The same skip rules apply inside <html-script> and <html-style>.
Skipped attributes only omit null, undefined, and false, writing NaN, "", and 0n.
Plain objects stringify to [object Object]. Render promises with <await> rather than interpolating the promise directly.
Unescaped Text
Prefix an interpolation with ! ($!{...}) to emit raw, unescaped HTML generated and sanitized elsewhere:
<article>$!{input.articleHtml}</article>export interface Input {
articleHtml: string;
}
<article>$!{input.articleHtml}</article>article -- $!{input.articleHtml}export interface Input {
articleHtml: string;
}
article -- $!{input.articleHtml}Unescaped interpolations write directly into the document and expose the page to XSS if given untrusted input.
Whitespace
Runs of whitespace in markup collapse to a single space. Any whitespace-only run that begins with a line break is removed completely, keeping source indentation out of the output. Both tags and ${...} placeholders act as boundaries for this rule.
<p>
Build finished in
<strong>12s</strong> <em>from cache</em>
</p>Renders:
<p>Build finished in <strong>12s</strong> <em>from cache</em></p>A line break immediately between tags or ${...} placeholders produces no space (<b>Total:</b> followed by a newline and ${amount} renders <b>Total:</b>5, and ${a} followed by a newline and ${b} renders AB). Keep a space on the same line when separation is needed.
Whitespace is preserved verbatim inside <pre>, <textarea>, <script>, <style>, <html-script>, and <html-style>.
Tag Variables
Tag variables expose reactive values from a tag into the template scope, written as / followed by an identifier or destructuring pattern. Custom tags expose values through <return>.
<my-tag/foo/>
<my-other-tag/{ bar, baz }/>
<div>${foo}</div>
<div>${bar}, ${baz}</div>my-tag/foo
my-other-tag/{ bar, baz }
div -- ${foo}
div -- ${bar}, ${baz}Native tags expose a getter function returning the DOM element (native tag variables must be a single identifier, not a destructuring pattern):
<div/myDiv/>
<script>
myDiv().innerHTML = "Hello";
</script>div/myDiv
script
--
myDiv().innerHTML = "Hello";
--Tag Var Scope
Function-valued tag variables (including native element references) are hoisted across the template body (excluding module statements). Non-function <let>, <const>, and <define> tag variables are scoped to their enclosing block.
<form>
<input/myInput>
</form>
<script>
console.log(myInput());
</script>form
input/myInput
script
--
console.log(myInput());
--Hoisted references are readable only in code that runs after render: <script> bodies, <lifecycle> hooks, and event handlers.
Attributes, <const>, and interpolations evaluate during render, before hoisted references are readable:
// ❌ `myInput` is read while the template renders
<div>${myInput().value}</div>// ❌ `myInput` is read while the template renders
div -- ${myInput().value}Repeated Tag Vars
When a hoisted tag variable originates inside a loop or repeated scope, it also implements the iterable protocol while calling it directly returns the first match:
<for until=10>
<div/$el/>
</for>
<script>
$el().style.color = "red";
let i = 0;
for (const el of $el) {
el.textContent = String(i++);
}
</script>for until=10
div/$el
script
--
$el().style.color = "red";
let i = 0;
for (const el of $el) {
el.textContent = String(i++);
}
--Tag Parameters
A tag can pass values back into its content as |parameters| enclosed in pipes after the tag name:
<div>
<${input.content} number=1337/>
</div>export interface Input {
content: Marko.Body<[{ number: number }]>;
}
<div>
<${input.content} number=1337/>
</div>div
${input.content} number=1337export interface Input {
content: Marko.Body<[{ number: number }]>;
}
div
${input.content} number=1337<child|params|>
Rendered with ${params.number} as the `number=` attribute.
</child>child|params| -- Rendered with ${params.number} as the `number=` attribute.Renders:
<div>Rendered with 1337 as the `number=` attribute.</div>Parameters support full JavaScript function parameter syntax, including destructuring (<child|{ number }|>).
Tag Arguments
Pass positional arguments instead of named attributes with (...args) after the tag name:
<${input.content}(1, 2, 3)/>export interface Input {
content: Marko.Body<[number, number, number]>;
}
<${input.content}(1, 2, 3)/>${input.content}(1, 2, 3)export interface Input {
content: Marko.Body<[number, number, number]>;
}
${input.content}(1, 2, 3)<child|a, b, c|>Sum ${a + b + c}</child>
<child|...all|>Sum ${all.reduce((a, b) => a + b, 0)}</child>child|a, b, c| -- Sum ${a + b + c}
child|...all| -- Sum ${all.reduce((a, b) => a + b, 0)}Custom tags accept either attributes or a single positional argument (with no body content). Dynamic tags and content bodies accept either attributes or multiple positional arguments (including spreads) alongside optional body content.
<my-tag a=1 b=2 c=3/>
// identical to
<my-tag({ a: 1, b: 2, c: 3 })/>my-tag a=1 b=2 c=3
// identical to
my-tag({ a: 1, b: 2, c: 3 })Tag Param Scope
Tag parameters are scoped strictly to the tag's content and are not accessible outside the body or inside attribute tags.
Doctype
A doctype writes directly to the HTML output in the template that renders the full document:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<status-board/>
</body>
</html><!doctype html>
html lang="en"
head
meta charset="utf-8"
body
status-boardContributors
Helpful? You can thank these awesome people! You can also edit this doc if you see any issues or want to improve it.
Comments
Both HTML and JavaScript comments are supported and stripped from rendered output:
To emit a literal HTML comment into the output, use
<html-comment>.