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

Note

Click 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:

  1. Any reactive value (tag variable, tag parameter, or input) read by the expression or effect using $signal changes, including reads inside callbacks it registers
  2. The template or tag content is removed from the DOM
Caution

$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.

Tip

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>";

MyTag

Lazy 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.data

See 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`);
}

Tags

Marko supports all native HTML, SVG, and MathML tags alongside core tags and custom tags (local or installed via node_modules). All tags share the same syntax:

<my-tag/>
my-tag

Any tag without content may be self-closed (<div/>). Void elements such as <input> and <br> require neither a closing tag nor a trailing /.

Any closing tag may omit its name:

<div>Hello World</>

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).

Caution

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).

Caution

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 * 2

Skipped 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=true
Important

ARIA 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 Me

Native 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() } -- Save

Shorthand 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.countChange

Refining 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=1

Combining 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=2
Caution

Wrap 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:

card.marko
<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}
index.marko
<card>Content</card>
card -- Content

Native 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.content

Dynamic 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>.

Note

Skipped attributes only omit null, undefined, and false, writing NaN, "", and 0n.

Warning

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}
Caution

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>
Warning

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>.

Attribute Tags

Tags prefixed with @ pass named or repeated sections of content and attributes into the parent tag's input instead of rendering directly:

index.marko
<my-layout title="Welcome">
  <@header class="banner">
    <h1>Big things are coming!</h1>
  </@header>

  <p>Page body</p>
</my-layout>
my-layout title="Welcome"
  @header class="banner"
    h1 -- Big things are coming!

  p -- Page body
tags/my-layout.marko
<header class=input.header.class>
  <${input.header.content}/>
</header>
<main>
  <${input.content}/>
</main>
export interface Input {
  title: string;
  header: Marko.AttrTag<{
    class: string;
    content: Marko.Body;
  }>;
  content: Marko.Body;
}

<header class=input.header.class>
  <${input.header.content}/>
</header>
<main>
  <${input.content}/>
</main>
header class=(input.header.class)
  ${input.header.content}
main
  ${input.content}
export interface Input {
  title: string;
  header: Marko.AttrTag<{
    class: string;
    content: Marko.Body;
  }>;
  content: Marko.Body;
}

header class=input.header.class
  ${input.header.content}
main
  ${input.content}

<my-layout> receives:

{
  title: "Welcome",
  header: {
    class: "banner",
    content: /* <h1>Big things are coming!</h1> */,
  },
  content: /* <p>Page body</p> */,
}
Note

Control flow tags (<if> and <for>) pass nested attribute tags upward to their enclosing tag; see Conditional Attribute Tags.

Nested Attribute Tags

Attribute tags can nest inside other attribute tags, becoming properties on their parent attribute tag:

<my-tag>
  <@a value=1>
    <@b value=2/>
  </@a>
</my-tag>
my-tag
  @a value=1
    @b value=2

Provides the following input:

{
  a: {
    value: 1,
    b: { value: 2 },
  },
}

Repeated Attribute Tags

When an attribute tag appears multiple times with the same name, the property exposes the first instance directly and implements the iterable protocol over all instances:

index.marko
<my-menu>
  <@item value="foo">Foo Item</@item>
  <@item value="bar">Bar Item</@item>
</my-menu>
my-menu
  @item value="foo" -- Foo Item
  @item value="bar" -- Bar Item
tags/my-menu.marko
<for|item| of=input.item>
  Value: ${item.value}
  <${item.content}/>
</for>
export interface Input {
  item?: Marko.AttrTag<{
    value: string;
    content: Marko.Body;
  }>;
}

<for|item| of=input.item>
  Value: ${item.value}
  <${item.content}/>
</for>
for|item| of=input.item
  -- Value: ${item.value}
  ${item.content}
export interface Input {
  item?: Marko.AttrTag<{
    value: string;
    content: Marko.Body;
  }>;
}

for|item| of=input.item
  -- Value: ${item.value}
  ${item.content}

Use singular names for attribute tags (<@item>, iterated as input.item) even when repeated.

Tip

Spread a repeated attribute tag into an array when random access or .length is needed:

<const/items=[...(input.item || [])]>
<div>${items.length}</div>
export interface Input {
  item?: Marko.AttrTag<{}>;
}

<const/items=[...(input.item || [])]>
<div>${items.length}</div>
const/items=[...(input.item || [])]
div -- ${items.length}
export interface Input {
  item?: Marko.AttrTag<{}>;
}

const/items=[...(input.item || [])]
div -- ${items.length}

Conditional Attribute Tags

<if> and <for> apply attribute tags dynamically to their enclosing tag:

<my-message>
  <if=welcome>
    <@title>Hello</@title>
  </if>
  <else>
    <@title>Goodbye</@title>
  </else>
</my-message>
my-message
  if=welcome
    @title -- Hello
  else
    @title -- Goodbye
<my-select>
  <@option>None</@option>
  <for|opt| of=["a", "b", "c"]>
    <@option>${opt}</@option>
  </for>
</my-select>
my-select
  @option -- None
  for|opt| of=["a", "b", "c"]
    @option -- ${opt}
Note

A control flow branch may contain attribute tags or default content, not both in the same branch.

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.

Warning

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:

child.marko
<div>
  <${input.content} number=1337/>
</div>
export interface Input {
  content: Marko.Body<[{ number: number }]>;
}

<div>
  <${input.content} number=1337/>
</div>
div
  ${input.content} number=1337
export interface Input {
  content: Marko.Body<[{ number: number }]>;
}

div
  ${input.content} number=1337
parent.marko
<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:

child.marko
<${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)
parent.marko
<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-board

Comments

Both HTML and JavaScript comments are supported and stripped from rendered output:

<div>
  <!-- HTML comment -->
  // JavaScript line comment
  /* JavaScript block comment */
</div>
div
  <!-- HTML comment -->
  // JavaScript line comment
  /* JavaScript block comment */
Note

To emit a literal HTML comment into the output, use <html-comment>.

Dynamic Tags

An ${expression} in the tag name position renders a native tag, custom tag, or tag content dynamically. Close dynamic tags with </> or self-close with />.

Dynamic Native Tags

When the expression evaluates to a string, Marko renders a native HTML element with that tag name:

<${"h" + input.headingSize}>Hello!</>
export interface Input {
  headingSize: 1 | 2 | 3 | 4 | 5 | 6;
}

<${"h" + input.headingSize}>Hello!</>
${"h" + input.headingSize} -- Hello!
export interface Input {
  headingSize: 1 | 2 | 3 | 4 | 5 | 6;
}

${"h" + input.headingSize} -- Hello!
Caution

String tag names write directly into the document and expose the page to XSS if untrusted. Never pass user-provided strings as dynamic tag names.

Dynamic Custom Tags

Pass an imported tag reference, <define> variable, or Marko.Body directly:

import MyTagA from "<my-tag-a>";
import MyTagB from "<my-tag-b>";

<${Math.random() > 0.5 ? MyTagA : MyTagB}/>
import MyTagA from "<my-tag-a>";
import MyTagB from "<my-tag-b>";

${Math.random() > 0.5 ? MyTagA : MyTagB}

Objects carrying a .content property (such as <define> tag variables) or a .default module export are unwrapped automatically.

Caution

Strings always render native HTML elements (document.createElement("my-tag-a")), never custom tags. Pass the imported tag reference instead:

// Renders a native `<my-tag-a>` or `<my-tag-b>` element, not a custom tag
<${Math.random() > 0.5 ? "my-tag-a" : "my-tag-b"}/>
// Renders a native `<my-tag-a>` or `<my-tag-b>` element, not a custom tag
${Math.random() > 0.5 ? "my-tag-a" : "my-tag-b"}

Conditional Parent Tags

When a dynamic tag name evaluates to a falsy value, Marko renders its content without a wrapper element:

<${input.href && "a"} href=input.href>Hello World</>
export interface Input {
  href?: string;
}

<${input.href && "a"} href=input.href>Hello World</>
${input.href && "a"} href=input.href -- Hello World
export interface Input {
  href?: string;
}

${input.href && "a"} href=input.href -- Hello World

PascalCase Variables

Any local variable starting with an uppercase letter (PascalCase) can be invoked directly as a tag without ${...}:

import MyTag from "./my-tag.marko";

<MyTag/>
// equivalent to
<${MyTag}/>
import MyTag from "./my-tag.marko";

MyTag
// equivalent to
${MyTag}
Warning

A dot in a tag name is parsed as the class shorthand, so <Toolbar.Undo/> renders Toolbar with class="Undo". Use dynamic tag syntax to render a property on an object:

<${Toolbar.Undo}/>
${Toolbar.Undo}

Contributors

Helpful? You can thank these awesome people! You can also edit this doc if you see any issues or want to improve it.