Skip to main content

HTML

zio-blocks-html is a type-safe HTML templating library providing immutable data structures and a fluent DSL for building HTML, CSS, and JavaScript. It offers compile-time safety, automatic XSS protection, and zero-dependency simplicity across Scala 2.13, 3.x, and both JVM and Scala.js platforms.

Core types: Dom (HTML tree), CssSelector (CSS queries), DomSelection (DOM navigation), Css (stylesheets), Js (JavaScript expressions).

The module is structured around these core types:

import zio.blocks.html._
import zio.blocks.chunk.Chunk

// Dom variants
sealed trait Dom
case class Dom.Text(content: String) extends Dom
sealed trait Dom.Element extends Dom
case class Dom.Element.Generic(tag: String, attributes: Chunk[Dom.Attribute], children: Chunk[Dom]) extends Dom.Element
case class Dom.Element.Script(attributes: Chunk[Dom.Attribute], children: Chunk[Dom]) extends Dom.Element
case class Dom.Element.Style(attributes: Chunk[Dom.Attribute], children: Chunk[Dom]) extends Dom.Element
sealed trait Dom.Element.Void extends Dom // void elements (self-closing, no children)
case class Dom.Element.VoidGeneric(tag: String, attributes: Chunk[Dom.Attribute]) extends Dom.Element.Void

// Sealed content-model markers (implemented by dedicated element classes)
sealed trait Dom.Element.Li extends Dom.Element // <li>, child of ul/ol
sealed trait Dom.Element.Cell extends Dom.Element // <th> or <td>, child of tr
sealed trait Dom.Element.Th extends Dom.Element.Cell
sealed trait Dom.Element.Td extends Dom.Element.Cell
sealed trait Dom.Element.Tr extends Dom.Element // <tr>, child of table
sealed trait Dom.Element.SelectChild extends Dom.Element // <option> or <optgroup>, child of select
sealed trait Dom.Element.Opt extends Dom.Element.SelectChild
sealed trait Dom.Element.Optgroup extends Dom.Element.SelectChild

// Attribute variants
sealed trait Dom.Attribute
case class Dom.Attribute.KeyValue(name: String, value: Dom.AttributeValue) extends Dom.Attribute
case class Dom.Attribute.AppendValue(name: String, value: Dom.AttributeValue, separator: Dom.AttributeSeparator) extends Dom.Attribute
case class Dom.Attribute.BooleanAttribute(name: String, enabled: Boolean) extends Dom.Attribute

// CssSelector variants (additional types omitted for brevity)
sealed trait CssSelector
case class CssSelector.Element(tag: String) extends CssSelector
case class CssSelector.Class(name: String) extends CssSelector

// Css variants
sealed trait Css
case class Css.Rule(selector: CssSelector, declarations: Chunk[Css.Declaration]) extends Css
final case class Css.Declaration private (property: String, value: String) // not a Css; built through Css.Declaration.apply

Motivation​

Why use zio-blocks-html?

String concatenation for HTML is error-prone:

  • No type safety — typos in tag names or attributes only surface at runtime
  • Manual escaping is tedious and easy to forget
  • Tightly couples HTML structure to data serialization

Template engines with runtime parsing add overhead and complexity:

  • Parsing validation on every render
  • Separate template syntax to learn
  • Difficult to compose programmatically

zio-blocks-html provides:

  • Type-safe construction via DSL functions (div(id := "main", p("Hello")))
  • Automatic XSS protection through position-aware typeclasses and HTML escaping
  • Scala 3 compile-time optimizations for string interpolators (constant folding, macro validation)
  • Zero dependencies — pure Scala, works with any HTTP framework
  • Cross-platform — identical API on JVM and Scala.js
  • Structured querying — CSS selectors for DOM navigation and testing

Installation​

Add to build.sbt:

libraryDependencies += "dev.zio" %% "zio-blocks-html" % "0.0.56"

For Scala.js projects, use %%%:

libraryDependencies += "dev.zio" %%% "zio-blocks-html" % "0.0.56"

Supported Scala versions: 2.13.x and 3.x

note

The html module depends directly on zio-blocks-schema and zio-blocks-chunk. The schema dependency enables ToJs auto-derivation via JSON encoding — if your type has a Schema instance, it automatically becomes usable in js"..." expressions.

Overview: How They Work Together​

The module is organized around five core subsystems that compose together:

┌─────────────────────────────────────────────────────┐
│ DSL Functions (div, p, span, ...) │
│ + Attribute Builders (id :=, className +=) │
│ └─> Produces: Generic / Void element nodes │
│ │
├─────────────────────────────────────────────────────┤
│ String Interpolators (html"", css"", js"") │
│ └─> Position-aware typeclasses │
│ └─> html"" → Dom.Element (attribute escaping) │
│ └─> css"" → Css (CSS value types) │
│ └─> js"" → Js (JavaScript with </script> guard) │
│ │
├─────────────────────────────────────────────────────┤
│ Dom ADT (sealed trait Dom) │
│ ├─> Dom.Text (HTML-escaped text content) │
│ ├─> Dom.Element (Generic, Script, Style) │
│ ├─> Dom.Element.Void (void/self-closing elements) │
│ ├─> Dom.Doctype (<!DOCTYPE html>) │
│ └─> Dom.Empty (renders to nothing) │
│ │
├─────────────────────────────────────────────────────┤
│ Rendering │
│ ├─> dom.render → minified HTML String │
│ ├─> dom.render(indent=2) → pretty-printed String │
│ └─> Used in HTTP responses, testing │
│ │
├─────────────────────────────────────────────────────┤
│ CSS Selectors + DOM Querying │
│ ├─> CssSelector ADT (Element, Class, Id, etc.) │
│ ├─> Fluent combinators (>, >>, +, ~, &, |) │
│ ├─> DomSelection API (select, filter, extract) │
│ └─> Used for testing, transformation, navigation │
└─────────────────────────────────────────────────────┘

Typical workflow:

  1. Build — use DSL (div(className := "card", ...)) or interpolators (html"<div>$content</div>")
  2. Compose — nest elements and use typeclasses to extend for custom types
  3. Query — use CSS selectors (page.select(div.hover).texts) for testing or transformation
  4. Render — call Dom#render or Dom#render(indent) for HTTP response or testing
  5. Style — use css"..." and Css.Rule to define or embed stylesheets

The Dom ADT​

The Dom sealed trait is the core data model. Everything in the module works with or produces Dom nodes.

The Node Types​

A Dom tree is composed of seven node types, described below: Text, Generic, Script, Style, Doctype, Empty and Dom.Element.Void (a node type of its own, described in Dom.Element.Void):

Dom.Text​

A text node containing string content. Text is automatically HTML-escaped when rendered to prevent XSS injection. Escaping happens at render time (not construction time), so Dom.Text stores the raw string.

To create text nodes, use the DSL (strings are converted via ToModifier[String]) or explicitly. Call Dom#render to convert a text node to an HTML string:

import zio.blocks.html._

val text = Dom.Text("Hello, world!")
// text: Text = Text("Hello, world!")
text.render
// res0: String = "Hello, world!"

Dom.Element.Generic​

A standard HTML element. The tag is the element name, attributes is a Chunk of key-value pairs and modifiers, and children is a Chunk of DOM nodes. Text content in children is HTML-escaped during rendering.

The DSL functions (div, p, span, etc.) construct these:

import zio.blocks.html._

val elem = div(id := "main", p("Content"))

Dom.Element.Script​

A specialized script element with tag = "script". Unlike Generic, Script renders its text children without HTML escaping, allowing inline JavaScript to be emitted as-is. This is the mechanism that enables safe js"..." interpolation — the interpolator escapes the JavaScript, but the Script element does not double-escape.

Use script().inlineJs(js"...") or script().externalJs(url):

import zio.blocks.html._

val inlineScript = script().inlineJs(js"console.log('Hello');")
val externalScript = script().externalJs("/app.js")

Dom.Element.Style​

A specialized style element with tag = "style". Like Script, Style renders text children without escaping, allowing raw CSS to be emitted. Use style().inlineCss(css"..."):

import zio.blocks.html._

val inlineStyle = style().inlineCss(css"body { margin: 0; }")

Dom.Doctype​

A DOCTYPE declaration node. Renders as <!DOCTYPE value>. The singleton doctype value renders as <!DOCTYPE html>:

import zio.blocks.html._

doctype.render
// res4: String = "<!DOCTYPE html>"

Dom.Empty​

A no-op node that renders to empty string. Useful for conditional rendering (e.g., if (condition) element else Dom.Empty).

Attributes and Values​

Elements carry a Chunk[Dom.Attribute] where each attribute is one of:

  • Dom.Attribute.KeyValue(name: String, value: Dom.AttributeValue) — A standard name="value" attribute. The value can be a string, multi-value, boolean, or JavaScript expression.

  • Dom.Attribute.AppendValue(name: String, value: Dom.AttributeValue, separator: Dom.AttributeSeparator) — Declares a value to be concatenated with any existing value for the same attribute. Provides accumulation of multi-valued attributes like class and rel. The separator appears between values (Space, Comma, Semicolon, or Custom).

  • Dom.Attribute.BooleanAttribute(name: String, enabled: Boolean) — A standalone attribute (like disabled, checked, required) that renders as just the name when enabled, or is omitted when disabled.

tip

The DSL provides id := value (:=) for single-valued attributes and className += "class" (+=) for appending to multi-valued attributes. Both are easier to use than constructing Dom.Attribute directly.

Tree Traversal Operations​

Dom provides four pure tree transformation methods:

Dom#collect(pf: PartialFunction[Dom, Dom]): List[Dom] — Applies a partial function to every node in the tree (depth-first) and collects the results. Useful for extracting or transforming specific nodes:

import zio.blocks.html._

val tree = div(p("A"), span("B"), p("C"))
val paragraphs = tree.collect { case el: Dom.Element if el.tag == "p" => el }

Dom#filter(predicate: Dom => Boolean): Dom — Removes any node for which the predicate returns false. A failing child is removed from its parent together with its subtree; when the root itself fails, the result is Dom.Empty. Matching elements have their children recursively filtered:

import zio.blocks.html._

val tree = div(p("A"), span("Keep"), p("B"), span("Also keep"))
val filtered = tree.filter {
case el: Dom.Element => el.tag == "div" || el.tag == "span"
case _ => true
}

Dom#find(predicate: Dom => Boolean): Option[Dom] — Returns the first node (depth-first) matching the predicate, or None:

import zio.blocks.html._

val tree = div(p("First"), span("Second"), p("Third"))
tree.find { case el: Dom.Element => el.tag == "p"; case _ => false }

Dom#transform(f: Dom => Dom): Dom — Applies a transformation function to every node in pre-order. Each node receives the transformation first, and if it is an Element, its children are recursed on the transformed node, so a transformation that changes the child list affects what gets recursed into:

import zio.blocks.html._

val tree = div(h3("Old"), p("Content"))
val upgraded = tree.transform {
case el: Dom.Element.Generic if el.tag == "h3" => el.copy(tag = "h2")
case other => other
}

The HTML DSL​

The DSL provides functions for all HTML5 elements, allowing fluent construction with a modifier pattern.

Element Functions​

All standard HTML elements are available as lowercase functions (or backtick-quoted if they shadow Scala keywords):

import zio.blocks.html._

// Basic elements
val paragraph = p("Hello, world!")
val heading = h1("Welcome")
val container = div("Content here")

// Void elements (auto self-closing)
val image = img(src := "photo.jpg", alt := "A photo")
val lineBreak = br
val horizontalRule = hr

// Keyword-shadowed elements (use backticks)
val objElement = `object`("data.bin")

Tag Names That Clash With Your Imports​

import zio.blocks.html._ brings a member for every tag, so some tag names collide with names from other imports or with your own helpers. The compiler reports these clashes as ambiguous references or as type errors that point somewhere else, so it helps to know them in advance:

  • span and scala.concurrent.duration._. A wildcard import of scala.concurrent.duration._ also brings an object named span into scope, so span("1") fails with "Reference to span is ambiguous". Import only the extension you need, such as scala.concurrent.duration.DurationInt, and keep the DSL's span.
  • main inside an object that defines def main(args: Array[String]). A call to main(id := "main")(...) resolves to your method, and the error names Array[String], not the element. Qualify the element as zio.blocks.html.main(...), or rename the import.
  • Tag names as helper names. Names such as search, title, select, label, header, option, data, time and output clash with helpers of the same name, such as a def search(query: String) that you import with a wildcard. Import your own helpers by name, or rename them.

Import only the duration extension next to the DSL:

import scala.concurrent.duration.DurationInt
import zio.blocks.html._

val delay = 300.millis
val banner = span(id := "banner")("Saved")

Qualify the element inside an object with its own main method:

import zio.blocks.html._

object Layout {
def page: Dom.Element = html(body(zio.blocks.html.main(id := "main")("content")))

def main(args: Array[String]): Unit = println(page.render)
}

Setting Attributes​

Attributes are set using the := operator on AttributeKey builders:

import zio.blocks.html._

val link = a(
href := "https://example.com",
target := "_blank",
titleAttr := "Visit Example",
"Visit Example"
)

Multi-Valued Attributes: Override vs Accumulate​

For attributes that can have multiple values (class, rel), you can override or accumulate:

  • := (override) — Replaces any earlier := value, so the last := wins. Values added with += are always appended, so className += "sale", className := "card" renders class="card sale":
import zio.blocks.html._

val div1 = div(className := "a", className := "b")
  • += (append) — Concatenates with the previous value using a separator (space for class):
import zio.blocks.html._

val div2 = div(className += "card", className += "active")
  • Mixed — Set a base value, then append:
import zio.blocks.html._

val div3 = div(className := "base").when(true)(className += "extra")

Boolean Attributes​

Use BooleanAttribute.:= to conditionally include attributes like disabled, required, or checked:

import zio.blocks.html._

val isDisabled = true
val submitBtn = button(disabled := isDisabled, "Submit")

Data and ARIA Attributes​

Use dataAttr(name) and aria(name) builders for HTML5 data attributes and ARIA accessibility attributes:

import zio.blocks.html._

val userDiv = div(
dataAttr("user-id") := "42",
dataAttr("action") := "edit",
"User Card"
)

val closeBtn = button(
aria("label") := "Close",
aria("expanded") := "false",
"×"
)

For custom attributes not provided by the DSL, use the generic attr(name) builder:

import zio.blocks.html._

val alpineDiv = div(attr("x-data") := "{open: false}", "Alpine.js component")
val htmxDiv = div(attr("hx-get") := "/api/data", "HTMX target")

Programmatic Multi-Valued Attributes​

For programmatic construction of multi-valued attributes (when the DSL += operator is not available), use Dom.multiAttr(name) or Dom.multiAttr(name, separator):

import zio.blocks.html._

// Create a custom multi-valued attribute builder (alternative to DSL's className)
val classBuilder = Dom.multiAttr("class")
val div1 = div(classBuilder := "base", classBuilder += "active")

// Create a multi-valued attribute with explicit separator
val rel = Dom.multiAttr("rel", Dom.AttributeSeparator.Space)
val link = a(rel := "prev", rel += "first", href := "/previous")

The MultiAttributeKey class handles accumulation of values with configurable separators (Space, Comma, Semicolon, or Custom).

For constructing multi-valued attributes directly from collections (without a builder chain), use the Iterable[String] overload:

import zio.blocks.html._

// Directly create a multi-valued attribute from a collection
val customClasses = Dom.multiAttr("class", List("card", "active", "large"))
val div1 = div(customClasses)

This approach is useful when programmatically building multi-valued attributes outside the DSL's builder pattern.

Children​

Children can be strings, elements, or collections. The DSL uses the ToModifier typeclass to convert values into DOM nodes:

import zio.blocks.html._

// String children are converted to Dom.Text
val simple = p("Plain text")

// Element children are nested
val nested = div(p("First"), p("Second"))

// Lists of children — elements append directly, no wrapper
val items = List("Apple", "Banana", "Cherry")
val listEl = ul(items.map(item => li(item)))

Conditional Rendering​

Use when(condition) to apply modifiers conditionally:

import zio.blocks.html._

val isHighlighted = true
val box = div(
className := "box"
).when(isHighlighted)(
className += "highlighted",
titleAttr := "This is highlighted"
)

Use whenSome(option) to apply modifiers based on an Option:

import zio.blocks.html._

val maybeTitle: Option[String] = Some("Important")
val card = div(
className := "card",
p("Content")
).whenSome(maybeTitle)(t => Seq(
titleAttr := t,
className += "has-title"
))

DomModifier and the Conversion Type Classes​

Everything passed to an element factory becomes a DomModifier — a deferred description of one modification, collected during construction and applied in a batch. The ADT has four cases:

sealed trait DomModifier {
def applyTo(element: Dom.Element): Dom.Element
}

object DomModifier {
final case class AddAttr(attr: Dom.Attribute) extends DomModifier
final case class AddChild(child: Dom) extends DomModifier
final case class AddChildren(children: Chunk[Dom]) extends DomModifier
final case class AddEffects(effects: Chunk[DomModifier]) extends DomModifier
}

AddEffects is what makes the ADT recursive, so a group of modifications can be passed as one value and applied as a unit.

DomModifier#applyTo applies a single effect and returns the modified element. It is the direct path, and the one to avoid in a loop:

import zio.blocks.html._

val withId = DomModifier.AddAttr(id := "main").applyTo(div)

Each call produces a fresh element, so applying effects one at a time allocates an intermediate per effect:

withId.render
// res24: String = "<div id=\"main\"></div>"
Prefer the factory for multiple effects

A factory call such as div(a, b, c) applies every effect in one pass. Calling DomModifier#applyTo repeatedly rebuilds the element each time. Use DomModifier#applyTo for a single effect computed at runtime, and the factory syntax for everything else.

DomModifierConversions supplies the implicit that turns any A with a ToModifier[A] instance into a DomModifier, which is why strings, elements, and collections can be passed to a factory interchangeably.

ToDom​

ToDom[A] converts a value into a Dom node. It is contravariant, and the instance set covers Dom itself, Dom.Element, Dom.Text, String, Int, Long, Double, Boolean, plus derived instances for Option and Iterable.

The two derived instances have behaviour worth knowing, because both can produce a node you did not write. None becomes Dom.Empty, which renders as nothing:

import zio.blocks.html._

val absent = ToDom[Option[String]].toDom(None)
val present = ToDom[Option[String]].toDom(Some("hello"))

That is what lets an optional value be dropped into a template without a conditional:

absent.render
// res26: String = ""
present.render
// res27: String = "hello"

Iterable is the surprising one. An empty collection becomes Dom.Empty and a single-element collection becomes that element, but two or more elements are wrapped in a <span>:

ToDom[Iterable[String]].toDom(Nil).render
// res28: String = ""
ToDom[Iterable[String]].toDom(List("a")).render
// res29: String = "a"
ToDom[Iterable[String]].toDom(List("a", "b")).render
// res30: String = "<span>ab</span>"
Collections of two or more get a wrapper element

ToDom has to return a single Dom, so a multi-element Iterable is wrapped in a <span>. That inserts an element into your markup which is invalid inside <ul>, <table>, and <select>, and which affects CSS descendant selectors. To splice a collection without a wrapper, pass it to a factory — ul(items.map(li(_))) uses the collection overload and adds the children directly.

ToText​

ToText[A] converts a value to a plain String rather than a DOM node. Instances cover String, Int, Long, Double, Float, Boolean, Char, Byte, Short, BigInt, and BigDecimal:

ToText[Int].toText(42)
// res31: String = "42"
ToText[BigDecimal].toText(BigDecimal("1.50"))
// res32: String = "1.50"

There is deliberately no ToText[Dom]: rendering an element to text is Dom#render, whereas ToText is for values that are already scalar.

Dom.Element.Void​

Void HTML elements (br, hr, img, input, meta, link, area, base, col, embed, param, source, track, wbr) are a separate type from Dom.Element — they extend Dom.Element.Void which extends Dom directly (not Dom.Element). This means they structurally cannot have children — passing a modifier like a string or another element to a void element factory is a compile-time error:

import zio.blocks.html._

img("oops") // ❌ does not compile — Void elements don't accept children
input(div("child")) // ❌ does not compile — Void elements don't accept children
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 17 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 20
//
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 20 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 26
//
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 26 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 29
//
// error:
// Conflicting definitions:
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 64 and
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 88
//
// error:
// Conflicting definitions:
// val link: zio.blocks.html.Dom.Element in class MdocApp0 at line 57 and
// val link: zio.blocks.html.Dom.Element in class MdocApp0 at line 90
//
// error:
// Conflicting definitions:
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 88 and
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 93
//
// error:
// Found: ("oops" : String)
// Required: zio.blocks.html.Dom.Attribute
// error:
// Found: zio.blocks.html.Dom.Element
// Required: zio.blocks.html.Dom.Attribute

Void elements only accept Dom.Attribute arguments:

import zio.blocks.html._

val image = img(src := "photo.jpg", alt := "A photo") // ✅ compiles — only attributes
val lineBreak = br // ✅ compiles — no args
val textField = input(`type` := "text", placeholder := "Enter text") // ✅ compiles

Void elements render as self-closing tags:

import zio.blocks.html._

val voidElements = div(
br,
hr,
img(src := "photo.jpg", alt := "A photo"),
input(`type` := "text", placeholder := "Enter text")
)

Typed Content Models​

Several container elements enforce the HTML content model of their children at compile time. Instead of accepting arbitrary modifiers, these factories only accept attributes plus children whose type matches the content model:

FactoryAccepted element childrenMarker type
ul(...), ol(...)<li>Dom.Element.Li
tr(...)<th>, <td>Dom.Element.Cell (Th | Td)
table(...)<tr>Dom.Element.Tr
select(...)<option>, <optgroup>Dom.Element.SelectChild (Opt | Optgroup)
optgroup(...)<option>Dom.Element.Opt

Invalid children are rejected by the compiler:

import zio.blocks.html._

ul(div("not a list item")) // ❌ does not compile — ul only accepts Li children
tr(p("not a cell")) // ❌ does not compile — tr only accepts Th/Td cells
select(div("not an option")) // ❌ does not compile — select only accepts option/optgroup
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 17 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 20
//
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 20 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 26
//
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 26 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 29
//
// error:
// Conflicting definitions:
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 64 and
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 88
//
// error:
// Conflicting definitions:
// val link: zio.blocks.html.Dom.Element in class MdocApp0 at line 57 and
// val link: zio.blocks.html.Dom.Element in class MdocApp0 at line 90
//
// error:
// Conflicting definitions:
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 88 and
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 93
//
// error:
// None of the overloaded alternatives of method ul in trait HtmlElements with types
// (children: Iterable[zio.blocks.html.Dom.Element.Li]):
// zio.blocks.html.Dom.Element
// (effect: zio.blocks.html.Dom.Attribute | zio.blocks.html.Dom.Element.Li, effects
// : (zio.blocks.html.Dom.Attribute | zio.blocks.html.Dom.Element.Li)*):
// zio.blocks.html.Dom.Element
// (): zio.blocks.html.Dom.Element
// match arguments (zio.blocks.html.Dom.Element)
// error:
// None of the overloaded alternatives of method tr in trait HtmlElements with types
// (children: Iterable[zio.blocks.html.Dom.Element.Cell]):
// zio.blocks.html.Dom.Element.Tr
// (effect: zio.blocks.html.Dom.Attribute | zio.blocks.html.Dom.Element.Cell,
// effects: (zio.blocks.html.Dom.Attribute | zio.blocks.html.Dom.Element.Cell)*)
// : zio.blocks.html.Dom.Element.Tr
// (): zio.blocks.html.Dom.Element.Tr
// match arguments (zio.blocks.html.Dom.Element)
// error:
// None of the overloaded alternatives of method select in trait HtmlElements with types
// (children: Iterable[zio.blocks.html.Dom.Element.SelectChild]):
// zio.blocks.html.Dom.Element
// (
// effect: zio.blocks.html.Dom.Attribute |
// zio.blocks.html.Dom.Element.SelectChild,
// effects: (zio.blocks.html.Dom.Attribute |
// zio.blocks.html.Dom.Element.SelectChild)*): zio.blocks.html.Dom.Element
// (): zio.blocks.html.Dom.Element
// match arguments (zio.blocks.html.Dom.Element)
// select(div("not an option")) // ❌ does not compile — select only accepts option/optgroup
// ^^^^^^

Attributes are accepted alongside the constrained children:

import zio.blocks.html._

val list = ul(id := "menu", className := "nav", li("Home"), li("About"))
val row = tr(className := "header-row", th("Name"), td("Value"))
val picker = select(id := "color", name := "color", option("Red"), optgroup(option("Light"), option("Dark")))

Each factory has three forms: empty (ul()), mixed attributes and children (ul(id := "x", li("a"))), and collections of children (ul(items.map(item => li(item)))).

The typed factories produce elements carrying a sealed marker type (Li, Cell, Tr, SelectChild, ...). The markers are sealed — their implementations live inside the module — so a value typed Dom.Element.Li is guaranteed to render as <li>; the DSL factories are the intended construction path. Elements with permissive content models (li, th, td, option) keep accepting any flow content through the regular modifier API.

note

caption, colgroup, thead, tbody, and tfoot do not have typed markers yet, so tables containing them cannot be built with the table(...) factory. Compose those tables with the html"" interpolator or generic elements.

How the Constraint Is Encoded​

The guarantee is the same on both Scala versions, but the signature achieving it is not. Scala 3 uses a union type directly; Scala 2 has no unions, so each constrained factory takes a sealed argument trait with implicit conversions into it:

sealed trait ListArg
object ListArg {
final case class Attribute(value: Dom.Attribute) extends ListArg
final case class Item(value: Dom.Element.Li) extends ListArg

implicit def fromAttribute(attribute: Dom.Attribute): ListArg = Attribute(attribute)
implicit def fromLi(item: Dom.Element.Li): ListArg = Item(item)
}

def ul(effect: ListArg, effects: ListArg*): Dom.Element

Call sites are identical — ul(id := "menu", li("Home")) compiles unchanged on both — because the Scala 2 conversions are implicit. The encoding only becomes visible when you name the argument type, which is why these traits exist at all:

FactoryScala 2 argument typeScala 3 union
ul(...), ol(...)ListArgDom.Attribute | Dom.Element.Li
tr(...)CellArgDom.Attribute | Dom.Element.Cell
table(...)RowArgDom.Attribute | Dom.Element.Tr
select(...)SelectArgDom.Attribute | Dom.Element.SelectChild
optgroup(...)OptgroupArgDom.Attribute | Dom.Element.Opt
script(...)ScriptArgDom.Attribute | Js
style(...)StyleArgDom.Attribute | Css

ScriptArg and StyleArg follow the same shape: they are the argument types of script(...) and style(...).

Writing a function that forwards to one of these factories is where the difference surfaces. On Scala 2 the parameter type is the argument trait; on Scala 3 it is the union:

def menu(items: ListArg*): Dom.Element = ul(items.head, items.tail: _*)

Taking Iterable[Dom.Element.Li] avoids the difference entirely, since ul, ol, tr, table, optgroup and select each have a collection overload that is spelled the same on both versions (script and style have none).

Concrete Element Classes​

The marker traits are implemented by case classes named after their tag: LiElement, ThElement, TdElement, TrElement, OptElement, and OptgroupElement. Each holds attributes and children and hard-codes its tag, which is what makes a value typed Dom.Element.Li guaranteed to render as <li>.

You do not normally name them — the factories return the marker trait, not the implementation — but they appear in pattern matches over a DOM tree and in toString output. Because equality is structural, matching on Dom.Element.Generic will not catch a factory-produced li, even though the two are equal:

import zio.blocks.html._

val item = li("Home")

The factory returns the marker type, and the runtime class is the implementation behind it:

item.getClass.getSimpleName
// res38: String = "LiElement"

Matching against Generic at that static type does not merely fail — it does not compile. Dom.Element.Li and Generic are disjoint, so the compiler reports the case as unreachable:

item match {
case _: Dom.Element.Generic => "matched Generic"
case _ => "no match"
}
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 17 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 20
//
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 20 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 26
//
// error:
// Conflicting definitions:
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 26 and
// val tree: zio.blocks.html.Dom.Element in object MdocApp at line 29
//
// error:
// Conflicting definitions:
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 64 and
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 88
//
// error:
// Conflicting definitions:
// val link: zio.blocks.html.Dom.Element in class MdocApp0 at line 57 and
// val link: zio.blocks.html.Dom.Element in class MdocApp0 at line 90
//
// error:
// Conflicting definitions:
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 88 and
// val div1: zio.blocks.html.Dom.Element in class MdocApp0 at line 93
//

Widening to Dom.Element makes the match legal, and then Generic simply does not match:

val widened: Dom.Element = item
// widened: Element = LiElement(
// attributes = IndexedSeq(),
// children = IndexedSeq(Text("Home"))
// )
widened match {
case _: Dom.Element.Generic => "matched Generic"
case _: Dom.Element.Li => "matched Li"
case _ => "no match"
}
// res40: String = "matched Li"
Structural equality, disjoint types

li("Home") == Generic("li", ...) is true, but LiElement is not a Generic and never matches one. Equality is structural and crosses classes; the types do not. Match on the marker trait, or on Dom.Element plus tag, rather than on a concrete class.

Equality Across Element Classes​

Element equality is structural (tag + attributes + children + text-escaping semantics), independent of the concrete class. A factory-produced li(...) equals the structurally identical Generic("li", ...), and vice versa; equal elements also have equal hash codes:

import zio.blocks.html._
import zio.blocks.chunk.Chunk

val fromFactory = li("a")
val generic = Dom.Element.Generic("li", Chunk.empty, Chunk(Dom.Text("a")))
fromFactory == generic // true — structural equality across classes

Elements that render differently are never equal, even with identical fields: script/style render their children unescaped while Generic escapes them, so a Script never equals an equally-shaped Generic("script", ...) — equal elements always render identically.

String Interpolators​

The module provides four string interpolators: html"", css"", js"", and selector"". All offer compile-time safety (on Scala 3) and automatic escaping appropriate to their context.

html"" Interpolator​

The html"" interpolator is position-aware: it detects whether each interpolated argument is in an attribute-value position or content position, then summons the appropriate typeclass.

The html"" interpolator determines position based on the preceding string:

Position detection:

  • Attribute position: if the preceding string part ends with =, =', or =", the next argument is treated as an attribute value and uses ToAttrValue[A]
  • Content position: otherwise, the argument is treated as element content and uses ToElements[A]

Position-aware interpolation enables safe attribute values and content:

import zio.blocks.html._

val name = "Alice"
val age = 30

// name is in content position → ToElements[String]
// age is in attribute position (the whole value) → ToAttrValue[Int]
val elem = html"""<div id=$age class="profile">User: $name</div>"""

Single-root requirement: The html"" interpolator requires a single root element. Multiple top-level nodes cause an exception at runtime (Scala 2) or compile error for static templates (Scala 3). Whitespace around the root counts too: a template that starts or ends with a newline has three top-level nodes, so begin the template with the root tag and end it right after the closing tag. A $ inside a quoted attribute value, such as id="user-$age", is not supported in 0.0.56 (a known bug); interpolate the whole value instead, as in id=$age:

import zio.blocks.html._

// This compiles (single root)
val page = html"<div><p>A</p><p>B</p></div>"

XSS Protection:

Content interpolated into html"" is stored as Dom.Text nodes, which are HTML-escaped during Dom#render to prevent XSS:

import zio.blocks.html._

val userInput = "<script>alert('XSS')</script>"
val safe = html"<p>$userInput</p>"
danger

The html"" interpolator requires a single root element. On Scala 3, pure-static templates with multiple roots fail at compile time. On Scala 2 or for dynamic templates, the error occurs at evaluation time. Always wrap multiple elements in a container (e.g., <div>).

css"" Interpolator​

The css"" interpolator returns a Css value with ToCss typeclass dispatch for interpolated parts:

import zio.blocks.html._

val color = "blue"
val size = 16

val styles = css"color: $color; font-size: ${size}px;"

Use CssLength and CssColor types for type-safe CSS values:

import zio.blocks.html._

val width = css"width: ${CssLength(300.0, "px")};"
val background = css"background: ${CssColor.Hex.unsafe("ff0000")};"
note

CssColor.Hex returns Option[CssColor] because hex validation may fail. Use CssColor.Hex.apply() (or just CssColor.Hex(...)) for safe validation, or CssColor.Hex.unsafe() for known-valid hex strings.

js"" Interpolator​

The js"" interpolator returns a Js value. Strings are automatically quoted and escaped; numerics and booleans are rendered unquoted:

import zio.blocks.html._

val message = "Hello, world!"
val count = 42

val code = js"console.log($message); alert($count);"
warning

Never interpolate untrusted user input directly into js"". The interpolator escapes string values, but the Js value is rendered without additional escaping in script elements. Always use ToJs[String] (which automatically quotes and escapes) for any untrusted input.

The interpolator renders a String value as a quoted JavaScript literal, writing < and > as Unicode escapes:

import zio.blocks.html._

val userInput = "if (x < y) alert('<script>');"
// userInput: String = "if (x < y) alert('<script>');"
val code = js"let check = $userInput"
// code: Js = Js(
// "let check = \"if (x \\u003c y) alert(\\'\\u003cscript\\u003e\\');\""
// )

println(code.value)
// let check = "if (x \u003c y) alert(\'\u003cscript\u003e\');"

selector"" Interpolator​

The selector"" interpolator returns a CssSelector:

import zio.blocks.html._

val className = "active"
val selector = selector".$className"

CSS Selectors and the DSL​

The CssSelector ADT provides a fluent DSL for building CSS selectors with combinator methods.

Basic Selectors​

Create selectors for elements, classes, IDs, or universal matches:

import zio.blocks.html._

val divSel = CssSelector.Element("div")
val classSel = CssSelector.Class("container")
val idSel = CssSelector.Id("header")
val universal = CssSelector.Universal

Combinators​

All HTML elements (div, span, p, etc.) implement CssSelectable, so you can use them directly as selectors:

import zio.blocks.html._

// Element selectors via DSL elements
val divSel = div.selector
val childSel = div > span // div > span
val descendantSel = div >> span // div span (descendant)
val adjacentSel = div + span // div + span
val siblingSel = div ~ span // div ~ span
val andSel = div & CssSelector.Class("active") // div.active
val orSel = div | span // div, span

Pseudo-Classes and Pseudo-Elements​

Pseudo-classes match elements by their state, and pseudo-elements create dynamic content:

import zio.blocks.html._

val hoverSel = a.hover // a:hover
val firstChild = li().firstChild // li:first-child
val nthChild = tr().nthChild(2) // tr:nth-child(2)
val before = div.before // div::before
val after = span.after // span::after

Attribute Selectors​

Select elements by their attribute values using built-in matchers:

import zio.blocks.html._

val input = CssSelector.Element("input")

val hasType = input.withAttribute("type") // input[type]
val exactType = input.withAttribute("type", "text") // input[type="text"]
val containsClass = input.withAttributeContaining("class", "btn") // input[class*="btn"]
val startsWithHref = a.withAttributeStarting("href", "https") // a[href^="https"]
val endsWithPng = img.withAttributeEnding("src", ".png") // img[src$=".png"]

The Selector ADT​

The DSL operators are constructors: each one builds a CssSelector node, and the result is an ordinary sealed ADT you can pattern match on. That matters when a selector arrives from elsewhere — a stylesheet you are rewriting, a rule you are inspecting — rather than being written inline.

Every operator and its node:

ExpressionNodeRenders as
CssSelector.Element("div")Element(tag)div
CssSelector.Class("active")Class(name).active
CssSelector.Id("header")Id(name)#header
CssSelector.UniversalUniversal*
div > spanChild(parent, child)div > span
div >> spanDescendant(parent, descendant)div span
div + spanAdjacentSibling(previous, next)div + span
div ~ spanGeneralSibling(previous, sibling)div ~ span
div & CssSelector.Class("active")And(left, right)div.active
div | spanOr(left, right)div, span
a.hoverPseudoClass(inner, pseudoClass)a:hover
div.beforePseudoElement(inner, pseudoElement)div::before
input.withAttribute("type")Attribute(inner, attribute, matcher)input[type]
div.not(CssSelector.Class("hidden"))Not(inner, negated)div:not(.hidden)
CssSelector.Raw("...")Raw(value)verbatim

Because the nodes are recursive, a selector built with operators nests rather than flattening:

import zio.blocks.html._

val selector = div >> span & CssSelector.Class("active")

Matching on the outermost node tells you which operator produced it:

selector.render
// res54: String = "div span.active"
selector match {
case CssSelector.And(left, right) => s"And(${left.render}, ${right.render})"
case other => other.getClass.getSimpleName
}
// res55: String = "And(div span, .active)"

CssSelector.Raw is the escape hatch for syntax the ADT does not model. It renders verbatim, so nothing validates it:

CssSelector.Raw("div:has(> img)").render
// res56: String = "div:has(> img)"

Attribute Matchers​

CssSelector.Attribute carries an Option[AttributeMatch]. None tests for presence alone; the six matchers correspond to the CSS attribute operators:

BuilderMatcherRenders as
withAttribute(name)None[name]
withAttribute(name, value)Exact(value)[name="value"]
withAttributeContaining(name, value)Contains(value)[name*="value"]
withAttributeStarting(name, value)StartsWith(value)[name^="value"]
withAttributeEnding(name, value)EndsWith(value)[name$="value"]
withAttributeWord(name, value)WhitespaceContains(value)[name~="value"]
withAttributePrefix(name, value)HyphenPrefix(value)[name|="value"]

Every matcher has a builder, and building a CssSelector.Attribute node by hand gives the same selector:

div.withAttributeWord("class", "card").render
// res57: String = "div[class~=\"card\"]"
div.withAttributePrefix("lang", "en").render
// res58: String = "div[lang|=\"en\"]"
CssSelector.Attribute(
CssSelector.Element("div"),
"class",
Some(CssSelector.AttributeMatch.WhitespaceContains("card"))
) == div.withAttributeWord("class", "card")
// res59: Boolean = true

WhitespaceContains matches one word in a space-separated list, which is the correct matcher for a single class among several; HyphenPrefix matches a value or that value followed by a hyphen, which is what lang attributes need.

DOM Querying with DomSelection​

The DomSelection API lets you query and navigate DOM trees using CSS selectors. It is useful for testing, transforming templates, and extracting information.

Selecting Elements​

Call Dom#select(selector) to query the tree:

import zio.blocks.html._

val page = div(
header(nav(a(href := "/", "Home"), a(href := "/about", "About"))),
main(p(className += "intro", "Hello"), p("World")),
footer(p("© 2026"))
)

// Query by tag
val paragraphs = page.select(CssSelector.Element("p"))
paragraphs.length

// Query by class
val intros = page.select(CssSelector.Class("intro"))
intros.texts

The DomSelection API returned by Dom#select provides navigation methods like .children and .first to traverse the selection results:

import zio.blocks.html._

val page = div(
nav(a(href := "/", "Home"), a(href := "/about", "About")),
main(p("Content"))
)

// Direct children
val navLinks = page.select(CssSelector.Element("nav")).children

Extraction​

The DomSelection API provides methods like .attrs and .texts to extract attribute values and text content from selected elements:

import zio.blocks.html._

val page = div(
a(href := "/home", "Home"),
a(href := "/about", "About"),
a(href := "/contact", "Contact")
)

val hrefs = page.select(CssSelector.Element("a")).attrs("href")

Filtering​

The DomSelection API provides .filter and .withClass methods to filter selections by predicate or attribute:

import zio.blocks.html._

val page = div(
p(className += "visible", "A"),
p(className += "hidden", "B"),
p("C")
)

// Filter by predicate
val visible = page.select(CssSelector.Element("p")).filter {
case el: Dom.Element => el.attributes.exists {
case attr: Dom.Attribute.KeyValue if attr.name == "class" => true
case _ => false
}
case _ => false
}

// Filter by class
val withClass = page.select(CssSelector.Element("p")).withClass("visible")

Modifying Selections​

warning

DomSelection returns new copies with modifications; the original DOM tree remains unchanged. The DomSelection API provides functional transformations. To modify the original DOM tree, use Dom#transform with a tree-rewriting function, or rebuild the tree from scratch using the DSL.

The DomSelection API provides methods like .modifyAll, .replaceAll, and .removeAll to transform or replace selected nodes:

import zio.blocks.html._

val page = div(
p("Old 1"),
p("Old 2"),
span("Keep")
)

// Transform all Element nodes in the selection; non-Element nodes pass through unchanged
val modifiedSelection = page.select(CssSelector.Element("p")).modifyAll {
case el: Dom.Element.Generic if el.tag == "p" => el.copy(tag = "div")
case other => other
}

// Replace all selected nodes (returns DomSelection of replacement nodes)
val replacedSelection = page.select(CssSelector.Element("p")).replaceAll(p("New"))

// Remove all selected nodes (returns empty DomSelection)
val removedSelection = page.select(CssSelector.Element("p")).removeAll
note

Pseudo-class selectors (:hover, :focus, etc.) match elements structurally by their underlying element selector only — they cannot detect browser interaction state in a static DOM tree. div.hover matches the same elements as CssSelector.Element("div").

Adjacent sibling (+) and general sibling (~) selectors are supported in CSS output but not in DOM querying — DomSelection.select with these combinators returns empty results.

The CSS ADT​

The Css ADT represents structured stylesheets as a typed data structure, separate from strings.

All Css subtypes support .render() for minified output and .render(indent: Int) for indented pretty-printing:

  • Css.Rule — single CSS rule with selector and declarations
  • Css.Sheet — collection of rules
  • Css.Raw — raw CSS string
  • Css.Comment — CSS comment

Typed Values: Lengths and Colors​

A Css.Declaration takes its value as a String, so nothing stops "10pixels" or "#gggggg" from reaching a stylesheet. CssLength and CssColor are the typed alternatives: each validates on construction and renders itself, so an invalid value cannot be built rather than being caught downstream.

CssLength pairs a numeric value with a unit, and rejects units outside the CSS set — px, em, rem, %, vh, vw, ch, ex, vmin, vmax, cm, mm, in, pt, pc:

import zio.blocks.html._
import zio.blocks.html.CssLength._

The second import is what brings the numeric extension methods into scope. They live in object CssLength rather than the package, so import zio.blocks.html._ alone gives you the CssLength constructor but not 300.px.

Writing the constructor directly works, but the extension methods on Int and Double are shorter and produce the same value:

CssLength(300.0, "px").render
// res65: String = "300px"
300.px.render
// res66: String = "300px"
1.5.rem.render
// res67: String = "1.5rem"

CssLengthIntOps and CssLengthDoubleOps provide px, em, rem, pct, vh, and vw on numeric literals. pct is spelled out because % is not a legal method name:

50.pct.render
// res68: String = "50%"
100.vh.render
// res69: String = "100vh"

A whole-number Double renders without its decimal point, so 2.0.em and 2.em produce identical CSS:

2.0.em.render
// res70: String = "2em"
2.em.render
// res71: String = "2em"

CssColor is a sealed ADT with five cases, covering the notations CSS accepts:

CaseConstructorRenders as
CssColor.HexHex(value) / Hex.unsafe(value)#ff0000
CssColor.RgbRgb(r, g, b)rgb(255,0,0)
CssColor.RgbaRgba(r, g, b, a)rgba(255,0,0,0.5)
CssColor.HslHsl(h, s, l)hsl(0,100%,50%)
CssColor.NamedNamed(name)red

The numeric cases are plain case classes, so they need no validation step:

CssColor.Rgb(255, 0, 0).render
// res72: String = "rgb(255,0,0)"
CssColor.Rgba(255, 0, 0, 0.5).render
// res73: String = "rgba(255,0,0,0.5)"
CssColor.Hsl(0, 100, 50).render
// res74: String = "hsl(0,100%,50%)"

Hsl renders its saturation and lightness with percent signs while taking them as bare Ints, so pass 100 rather than 1.0 for full saturation.

CssColor.Hex and CssColor.Named are the two validated cases, and both return an Option from CssColor.Hex.apply rather than throwing:

CssColor.Hex("ff0000")
// res75: Option[CssColor] = Some(Hex("ff0000"))
CssColor.Hex("gggggg")
// res76: Option[CssColor] = None

A leading # is optional and the value is lowercased, so the same colour written four ways yields one representation:

CssColor.Hex("#FF0000").map(_.render)
// res77: Option[String] = Some("#ff0000")

CssColor.Hex.unsafe skips validation for literals you know are well-formed. It returns a CssColor directly rather than an Option, which is what makes it convenient inside an interpolator — and what makes it unsuitable for anything user-supplied:

CssColor.Hex.unsafe("ff0000").render
// res78: String = "#ff0000"
unsafe renders whatever it is given

CssColor.Hex.unsafe performs no checking, so Hex.unsafe("not-a-color") renders as #not-a-color and produces a stylesheet the browser silently ignores. Use it only for compile-time literals; route anything dynamic through CssColor.Hex.apply and handle the None.

Declarations and Rules​

A Css.Declaration is a property-value pair:

import zio.blocks.html._
import zio.blocks.chunk.Chunk

val marginDecl = Css.Declaration("margin", "10px")
val colorDecl = Css.Declaration("color", "blue")

val rule = Css.Rule(
CssSelector.Element("p"),
Chunk(marginDecl, colorDecl)
)

rule.render

Stylesheets​

A Css.Sheet is a collection of rules:

import zio.blocks.html._
import zio.blocks.chunk.Chunk

val bodyRule = Css.Rule(
CssSelector.Element("body"),
Chunk(
Css.Declaration("margin", "0"),
Css.Declaration("font-family", "sans-serif")
)
)

val stylesheet = Css.Sheet(Chunk(bodyRule))

stylesheet.render(indent = 2)

Embedding Stylesheets​

Embed stylesheets in HTML via the style() element:

import zio.blocks.html._
import zio.blocks.chunk.Chunk

val page = html(
head(
style().inlineCss(
Css.Sheet(Chunk(
Css.Rule(
CssSelector.Element("body"),
Chunk(Css.Declaration("background", "#f0f0f0"))
)
))
)
),
body(p("Styled"))
)

page.render

Raw CSS​

For CSS features not expressible via the ADT (media queries, keyframes, at-rules), use Css.Raw:

import zio.blocks.html._

val mediaQuery = Css.Raw("""
|@media (max-width: 600px) {
| body { font-size: 14px; }
|}
""".stripMargin)

println(mediaQuery.render)
tip

Prefer Css.Rule and Css.Sheet over Css.Raw when possible — structured CSS enables future optimization. Declaration values are not checked, so validate values that come from users. Use Css.Raw only for trusted, hardcoded CSS.

CSS Comments​

Add comments to stylesheets using Css.Comment:

import zio.blocks.html._
import zio.blocks.chunk.Chunk

val stylesheet = Css.Sheet(Chunk(
Css.Comment("Mobile-first responsive design"),
Css.Rule(
CssSelector.Element("body"),
Chunk(Css.Declaration("font-size", "16px"))
),
Css.Comment("Tablet and desktop breakpoints"),
Css.Raw("@media (min-width: 768px) { body { font-size: 18px; } }")
))

stylesheet.render(indent = 2)

Rendering​

All Dom and Css values support multiple rendering modes.

Minified Rendering​

Dom#render produces compact HTML with no extra whitespace. Use Dom#renderMinified as an explicit alias for the same operation:

import zio.blocks.html._

val page = div(h1("Title"), p("Content"))
page.render

Pretty-Printed Rendering​

render(indent: Int) produces indented, readable output:

import zio.blocks.html._

val page = div(h1("Title"), p("Content"))
page.render(indent = 2)

Performance Notes​

  • Dom#render uses a pre-allocated StringBuilder and while-loop rendering — zero allocations for iteration
  • Indentation strings get cached in an array of pre-built space strings (up to 128 characters) to prevent repeated string allocation
  • Void elements automatically self-close with no children
  • Script and Style elements render their children without escaping (with </ → <\/ protection for scripts)

Security: XSS Protection​

The module provides multiple layers of automatic XSS protection:

HTML Text Escaping​

All Dom.Text nodes are HTML-escaped during rendering:

  • & → &amp;
  • < → &lt;
  • > → &gt;
  • " → &quot;
  • ' → &#x27;

Untrusted content is always escaped to prevent XSS:

import zio.blocks.html._

val userInput = "<script>alert('XSS')</script>"
val safe = div(p(userInput))

safe.render

JavaScript String Escaping​

ToJs[String] renders a string as a quoted JavaScript literal. The characters <, > and & are written as \u003c, \u003e and \u0026, quotes and backslashes get a backslash, and line breaks are written as escapes. For example:

import zio.blocks.html._

val userInput = "</script><script>alert('XSS');</script>"
// userInput: String = "</script><script>alert('XSS');</script>"
val code = js"let payload = $userInput"
// code: Js = Js(
// "let payload = \"\\u003c/script\\u003e\\u003cscript\\u003ealert(\\'XSS\\');\\u003c/script\\u003e\""
// )

println(code.value)
// let payload = "\u003c/script\u003e\u003cscript\u003ealert(\'XSS\');\u003c/script\u003e"

URL Sanitization​

Attributes named href, src, action, or formaction are checked for dangerous schemes at render time:

  • javascript:, vbscript:, data:text/html → prefixed with unsafe:

Dangerous URLs are automatically sanitized in HTML output:

import zio.blocks.html._

val dangerous = a(href := "javascript:alert('XSS')", "Click me")

No Raw HTML Escape Hatch​

The module intentionally provides no Dom.Raw type for embedding arbitrary HTML. This prevents XSS by ensuring all dynamic content is either constructed via the DSL or interpolated through context-aware interpolators.

Common Patterns​

The module supports several architectural patterns for code organization and reuse:

Building Reusable Components​

Define functions that return Dom.Element to create reusable components:

import zio.blocks.html._

def card(title: String, content: String): Dom.Element =
div(
className := "card",
h2(title),
p(content)
)

val page = div(
card("Card 1", "Content A"),
card("Card 2", "Content B")
)

Conditional Rendering​

Use when and whenSome for conditional modifiers:

import zio.blocks.html._

def userCard(name: String, isAdmin: Boolean): Dom.Element =
div(
className := "user-card"
).when(isAdmin)(
className += "admin",
span(className := "badge", "Admin")
)

Rendering Collections​

Map over collections to create child elements:

import zio.blocks.html._

def userList(users: List[String]): Dom.Element =
ul(users.map(user => li(user)))

val page = userList(List("Alice", "Bob", "Charlie"))

Template Composition​

Combine interpolators and DSL for flexibility:

import zio.blocks.html._

val pageTitle = "My Page"
// pageTitle: String = "My Page"
val pageContent = "Welcome to my site"
// pageContent: String = "Welcome to my site"

val page = html"""<html>
<head><title>$pageTitle</title></head>
<body>
${div(p(pageContent))}
</body>
</html>"""
// page: Dom = Generic(
// tag = "html",
// attributes = IndexedSeq(),
// children = IndexedSeq(
// Text(
// """
// """
// ),
// Generic(
// tag = "head",
// attributes = IndexedSeq(),
// children = IndexedSeq(
// Generic(
// tag = "title",
// attributes = IndexedSeq(),
// children = IndexedSeq(Text("My Page"))
// )
// )
// ),
// Text(
// """
// """
// ),
// Generic(
// tag = "body",
// attributes = IndexedSeq(),
// children = IndexedSeq(
// Text(
// """
// """
// ),
// Generic(
// tag = "div",
// attributes = IndexedSeq(),
// children = IndexedSeq(
// Generic(
// tag = "p",
// attributes = IndexedSeq(),
// children = IndexedSeq(Text("Welcome to my site"))
// )
// )
// ),
// Text(
// """
// """
// )
// )
// ),
// Text(
// ...

println(page.render)
// <html>
// <head><title>My Page</title></head>
// <body>
// <div><p>Welcome to my site</p></div>
// </body>
// </html>

Querying for Tests​

Use DomSelection to write structural assertions:

import zio.blocks.html._

val page = div(
ul(
li(a(href := "/home", "Home")),
li(a(href := "/about", "About"))
)
)

// Test: check number of links
val links = page.select(CssSelector.Element("a"))
assert(links.length == 2)

// Test: check specific href
val aboutLink = page.select(a.withAttribute("href", "/about"))
assert(aboutLink.texts.contains("About"))

Complete Example: A Dashboard Page​

Here is a complete, self-contained example building a full dashboard page with navigation, metadata, styling, and content sections:

import zio.blocks.html._
import zio.blocks.chunk.Chunk

val userName = "Alice"
val items = List("Dashboard", "Settings", "Logout")

val pieces: Chunk[Dom] = Chunk(
doctype,
html(
head(
meta(charset := "utf-8"),
meta(name := "viewport", content := "width=device-width, initial-scale=1.0"),
title("My App"),
link(rel := "stylesheet", href := "/style.css"),
style().inlineCss(
Css.Sheet(Chunk(
Css.Rule(CssSelector.Element("body"), Chunk(
Css.Declaration("margin", "0"),
Css.Declaration("font-family", "sans-serif")
))
))
)
),
body(
header(
nav(items.map(item => a(href := "#", item)))
),
main(
h1(s"Welcome, $userName!"),
p("This is your dashboard.")
),
footer(
p("© 2026 My App")
),
script().inlineJs(js"console.log('Page loaded');")
)
)
)

pieces.map(_.render(indent = 2)).mkString("\n")

See also​