@chilts/weave
v0.8.0
Published
A Pug-inspired templating engine that compiles to TypeScript.
Maintainers
Readme
Weave
A Pug-inspired templating engine that compiles to TypeScript. Write indentation-based templates, get typed functions that return HTML.
views/*.weave → weave compiler → lib/views/*.ts → tscWhy Weave?
Pug is great. Weave takes the same indentation-based syntax and makes it TypeScript-native — your templates become typed functions, checked by tsc like any other code.
- Type-safe templates — template parameters are real TypeScript types
- Type-safe mixins — positional args with TS type annotations
- Tailwind-friendly — class names with colons (
.md:flex,.hover:bg-blue-500) just work, and dots escape (.gap-1\.5) - Single-pass escaping — values are escaped once at render time, never pre-escaped
- No runtime template engine — compiled output is plain TypeScript
Example
A type definition:
export interface SimpleProps {
title: string
content: string
}A .weave template:
import type { SimpleProps } from '../types/views.js'
template simple({ title, content }: SimpleProps)
doctype html
html(lang="en")
head
title= title
body
h1= title
p= contentCompiles to a .ts file:
import { h, doctype, Fragment } from "@chilts/weave"
import type { SimpleProps } from '../types/views.js'
export function simple({ title, content }: SimpleProps) {
return h(Fragment, {},
doctype(),
h("html", { lang: "en" },
h("head", {},
h("title", {}, title)
),
h("body", {},
h("h1", {}, title),
h("p", {}, content)
)
)
)
}Now tsc catches type errors, your IDE gives you autocomplete, and calling simple({ title: "Hello", content: "World" }) returns HTML.
Type-checking templates
tsc reports errors against the compiled .ts, which you never edit.
weave check compiles the templates, type-checks your whole project with your
tsconfig.json, and reports each error in a view at its .weave line:
$ npx weave check views/ lib/views/
weave: views/page.weave:3:5: Property 'nmae' does not exist on type '{ name: string; }'. TS2339
3 | h1= user.nmae
| ^
Found 1 error.It exits 1 on any error, so it can replace tsc --noEmit in CI, and the
file:line:col: format works with Emacs compile. It uses your project's
typescript package (install it as a dev dependency) and the nearest
tsconfig.json, or the one given with --project <path>. Errors point at the
exact token inside an expression, attribute value, condition, parameter or
argument, and at the start of the node for code Weave generated around them.
To map diagnostics yourself (from another tool or build step), use
mapDiagnostic({ file, line, col, message }), which translates a position in a
compiled .ts file to its .weave source via the .ts.map beside it, and
formatDiagnostic(), which prints the result with a code frame. Neither
depends on the typescript package.
Usage
Templates are just functions that return HTML, so they work with any framework.
Every template and mixin returns a SafeHtml, so its output isn't escaped
again when nested in another template. Call String() on it to get the HTML
string:
import express from 'express'
import { simple } from './lib/views/simple.js'
const app = express()
app.get('/', (req, res) => {
res.send(String(simple({ title: "Hello", content: "World" })))
})
app.listen(3000)Server-rendered apps and htmx
Weave is a good fit for apps that render HTML on the server and swap pieces of
it into the page — htmx, Turbo, Unpoly, or plain fetch.
- Every template and mixin is an exported function. Rendering a fragment for a swap is just calling the mixin; there is no partial-rendering API.
- The page and its fragments share one definition. The page loops over
+todoItem(todo), and the endpoint returnstodoItem(todo), so the markup can't drift apart. - No runtime engine, zero dependencies. The runtime is a few small helpers with no Node-specific imports, so compiled views run on Node, Deno, Bun and Cloudflare Workers alike.
A mixin for one row:
mixin todoItem(todo: Todo)
li.todo(id=`todo-${todo.id}` ...attrs)
input(
type="checkbox"
checked=todo.done
hx-post=`/todos/${todo.id}/toggle`
hx-target=`#todo-${todo.id}`
hx-swap="outerHTML"
)
span= todo.textThe page uses it in a loop, and the toggle endpoint returns just that row:
import { todoItem } from './lib/views/components/todo.js'
// POST /todos/:id/toggle
todo.done = !todo.done
return new Response(String(todoItem(todo)), {
headers: { 'content-type': 'text/html; charset=utf-8' },
})See examples/htmx/ for the full page, the mixin, and a
web-standard fetch handler serving both.
Syntax
Weave's syntax will be familiar if you've used Pug.
Elements, classes, IDs, and attributes
h1 Hello World
p.intro This is a paragraph with a class
.container
span#main.text-lg.md:text-xl Content here
a(href="/about" class="nav-link") AboutA . always starts a new class, so a class name that contains a dot — like Tailwind's gap-1.5 — must escape it with a backslash:
.flex.gap-1\.5.px-2\.5An unescaped .gap-1.5 would split into gap-1 and a stray 5, so a class that is a bare number is rejected with an error pointing at the fix.
Attributes
Attributes live inside parentheses and are separated by spaces. Every attribute must have a value — there is no valueless shorthand:
a(href="/about" class="nav-link") About
input(type="email" name="email")A value can be a quoted string, a template literal, or a bare TypeScript expression:
a(href=post.author.url)= post.author.title
button(class=`btn-${variant}`)= labelBoolean attributes
Write the boolean explicitly. The runtime renders true as a bare attribute and omits the attribute entirely when the value is false, undefined or null:
input(type="checkbox" checked=true) → <input type="checkbox" checked>
input(type="checkbox" checked=false) → <input type="checkbox">
input(type="checkbox" checked=isActive) → omitted when isActive is falseAvoid a quoted checked="false" — in HTML any attribute that is present counts as true, so that renders as checked.
Combining shorthand classes with class=
Shorthand classes and a class= value are merged into one attribute. The shorthand classes are always kept; a value of undefined, null, false or "" just adds nothing:
div.pt-4(class="mt-2") → <div class="pt-4 mt-2">
div.pt-4(class=undefined) → <div class="pt-4">
div.btn(class=(active ? "active" : undefined)) → <div class="btn"> when active is falseClass arrays and objects, style objects
class= also takes an array or an object, which suits conditional Tailwind classes. Arrays may nest and drop null, undefined, false and ""; an object keeps each key whose value is truthy. Both merge with shorthand classes:
div(class=(["a", "b"])) → <div class="a b">
li.item(class=({ active: isActive })) → <li class="item active"> when isActive is true
a(class=(["link", { "md:flex": wide }])) → <a class="link md:flex"> when wide is truestyle= takes an object of properties. camelCase keys become kebab-case, --custom properties are kept as written, and null, undefined, false and "" values are dropped:
div(style=({ marginTop: 0, "--gap": gap })) → <div style="margin-top:0;--gap:1rem">An array or object that yields nothing omits the attribute entirely. Numbers are not given units, so write "4px" rather than 4 where CSS needs one.
Multi-token values must be wrapped
Because a space separates one attribute from the next, a bare (unquoted) value has to be a single token. Wrap anything longer in parentheses or backticks:
main(class=(wide ? "px-6" : "mx-auto px-6"))
main(class=`${wide ? "" : "mx-auto "}px-6`)An unwrapped multi-token value is a compile error rather than a silent mis-parse. This is also why main(class=a b) is rejected: b could be part of the value or a separate attribute, so Weave asks you to say which you meant — class="a b" or class=a b="...".
Long attribute lists
An attribute list normally lives on one line. To split it over several lines, end
the line with the opening (, put one attribute per line, and close with a )
on a line of its own:
button.btn(
type="button"
class="rounded px-2"
aria-pressed=isActive
...attrs
)
| Toggle themeThe continuation lines have to be indented further than the element, and the
closing ) has to start its own line — aria-pressed=isActive) is an error. That
strictness is what makes a forgotten ) a local error instead of something that
swallows the rest of the file. Anything after the closing ) is read as trailing
content, so ) Toggle theme works too.
Everything else is unchanged: this is a layout choice, not a different grammar. Bare values still have to be a single token here, so a ternary still needs its wrapping parentheses.
A ( that is not at the end of its line must still close on that line:
a(href="/about"
class="nav-link") ← error: unterminated attribute listSpread
...attrs forwards a whole set of attributes, most often a mixin's implicit attrs:
button.btn(class=`btn-${variant}` ...attrs)= labelConditionals
if role === "admin"
p.badge You are an administrator
else if role === "editor"
p.badge You are an editor
else
p Welcome, visitorunless cond is a guard: its block renders when cond is falsy, the same as
if !(cond). It takes no else or else if — unless … else is a double
negative, so write an if with the branches swapped instead:
unless user.verified
p Please confirm your email address.Iteration
for ( const post of posts )
h2= post.title
p= post.content
else
p No posts yet.The optional else renders when the collection is empty. Any iterable works —
arrays, Set, Map, generators, or xs.entries() — and it is consumed once.
Mixins
Mixins use positional args. An implicit attrs parameter captures any extra attributes passed at the call site.
Definition:
mixin button(label: string, variant: "primary" | "secondary" = "primary")
button.btn(class=`btn-${variant}` ...attrs)= labelUsage:
+button("Save", "primary")(class="mr-2")
+button("Cancel", "secondary")
+button("Delete", "secondary")(class="ml-4" data-confirm="true")Call-site content
A bare block inside a mixin renders whatever is indented under the call,
so one mixin can wrap different content each time. Lines indented under
block are the default when the call has none, and if block tests for it:
mixin card(title: string)
.card(...attrs)
h2= title
block
p.muted Nothing to show.+card("Profile")(class="wide")
p= user.name
p= user.email
+card("Recent activity")The content is passed as a callback after attrs, so the call above compiles
to card("Profile", { class: "wide" }, () => ...). Named blocks (block
content) are layout slots and are not allowed inside a mixin. See
examples/mixin-block/.
One line of content can go on the call's own line instead, just as an
element takes inline text or = expr:
+btn("save") Save
+btn("save")(class="wide")= labelA call takes its content inline or indented, not both.
Layouts with extends and blocks
A layout defines named blocks as content slots:
template layout({ title }: LayoutProps)
doctype html
html(lang="en")
head
title= title
body
main
block content
footer
p © 2024The compiled layout takes its slots as a second blocks argument, typed by an
interface the compiler generates from the block names — you don't write it:
export interface LayoutBlocks {
content?: () => unknown
}
export function layout({ title }: LayoutProps, blocks: LayoutBlocks = {}) {A page extends the layout, filling in the blocks. Data is passed explicitly — nothing is implicitly inherited:
template home({ title, welcomeMessage }: HomeProps)
extends layout({ title })
block content
h1= welcomeMessage
p Welcome to our site.Blocks can have default content in the layout. If a page doesn't override a block, the default renders.
Long parameter lists
The parentheses after template, mixin, extends, for and a mixin call hold
TypeScript, which Weave copies through untouched. They can wrap over several lines
however TypeScript usually wraps: the group simply stays open until its parentheses
balance.
template dashboard({
title,
user,
}: DashboardProps)
h1= title
+card(
post.title,
post.summary,
)(class="mt-4")Unlike a long attribute list there is no required shape, but continuation lines must
be indented under the line that opens the group. The closing line may sit level with
it if it starts with a closing bracket, as }: DashboardProps) does. So a forgotten
) is reported where the indentation drops back. A string must close on the line it
starts on, and // comments are allowed but left out of the compiled output.
Includes
Include another .weave file to use its mixins:
include ./components/button
template actionsPage({ title }: ActionsPageProps)
doctype html
html(lang="en")
body
+button("Save", "primary")An included file can define any number of mixins. Weave reads it and imports
only the ones the template calls, so include ./partials followed by
+badge(...) and +chip(...) compiles to
import { badge, chip } from './partials.js'. Calling a mixin that is neither
defined in the file nor provided by an include is a compile error.
Text content
Use | (pipe) to add literal text as a child of an element:
p
| This is plain text inside a paragraph.A bare | on its own line (with no text after it) emits a single space. This is useful for adding whitespace between sibling elements:
p Hello
|
strong= email
| .This renders as: Hello <strong>[email protected]</strong>. — with a space between "Hello" and the email address.
Inline elements
Weave does not support inline element syntax (e.g. Pug's #[strong bold] tag interpolation), and #[ in text is a compile error. To mix elements within text, place each element on its own indented line and use | for spacing and text fragments. To show a literal #[ (or !{), use a string expression: p= "Use #[0] for the first item".
Raw blocks
Use ! after a tag to write literal content that won't be escaped or parsed as Weave syntax. This is useful for inline CSS, JavaScript, or any other content that should be passed through as-is:
style!
body { font-family: sans-serif; max-width: 640px; margin: 0 auto; }
h1 { border-bottom: 2px solid #eee; }script!
console.log("hello")The indented content is compiled to a raw() call, so the output is not HTML-escaped. Works with classes and IDs too: div.content!.
For inline raw expressions, use raw() directly: div.prose= raw(html).
Special characters
Weave escapes all text content by default. HTML entities like « will be escaped and rendered literally in the browser rather than interpreted. Use the actual Unicode character instead:
a(href="/back") « BackThis keeps the escaping model simple and predictable — all text is escaped, no exceptions.
Imports
Standard TypeScript imports pass through to the compiled output:
import type { BlogPost } from '../types/models.js'Coming from Pug
Most Pug templates read the same in Weave, but some Pug features are left out on purpose. Each one below is a compile error that names the Weave way to write it, rather than being silently mis-rendered.
| Pug | Weave |
|---|---|
| - const x = 1 (unbuffered code) | Templates hold no statements. Compute values in TypeScript before rendering, or use tag= expr |
| case / when / default | if / else if / else |
| each x in xs, while | for ( const x of xs ); for keys and values, for ( const [k, v] of Object.entries(obj) ) |
| p!= html | p= raw(html) |
| p Hi !{html} | p Hi #{raw(html)} |
| a(href!=url) | Attribute values are always escaped |
| p. (block text) | p! for raw text, or \| lines for escaped text |
| li: a Home (block expansion) | Put the child on its own indented line |
| #[strong bold] (tag interpolation) | Put each element on its own line; see Inline elements |
| foo/ (explicit self-closing) | Void elements like br and img close themselves |
| div&attributes(obj) | div(...obj) |
| input(disabled) | input(disabled=true); see Boolean attributes |
| extends ./layout | extends layout({ data }) calls the layout's template function and passes its data |
Filters (:markdown-it, include:markdown ./post.md) are not supported
and are not planned. Render the content in TypeScript and pass it in as a
raw() value.
block append / block prepend are not supported. A page replaces a
layout's block completely. When pages need to add to what the layout already
renders, give the layout a second, empty slot:
head
block scripts
script(src="/app.js")
block pageScriptsDynamic mixin calls (+#{name}()) are not supported. Mixins are ordinary
functions, so you can choose one at runtime with a buffered expression and
pass {} for its attrs: div= mixins[kind](item, {}).
Implicit scope. In Pug, included and extended templates can see their
caller's variables. In Weave, data only travels explicitly: through template
params, extends layout({ ... }) and mixin args.
Development
npm run build # compile TypeScript to dist/
npm test # lint, then type-check, then run tests (vitest)
npm run lint # lint with ESLint
npm run typecheck # type-check without emitting (tsc --noEmit)Status
Weave is usable today: the compiler, the weave CLI (with watch mode and source maps) and the runtime helpers are published on npm. It is still pre-1.0, so the syntax may change in a minor release — breaking changes are called out in CHANGELOG.md.
The examples/ directory pairs each .weave template with its compiled .ts. Every example is compiled in the test suite and compared byte-for-byte against that file, so they double as a reference for what the compiler emits.
Editor Support
- Emacs —
editors/emacs/— major mode with syntax highlighting, indentation, and comment support
Releases
See CHANGELOG.md for the full details of each release.
| Version | Date | Highlights |
|---------|------------|------------|
| 0.7.0 | 2026-10-20 | Multi-line parameter lists; escaped dots in class shorthand; include imports the mixins it provides; context-aware Emacs mode |
| 0.6.0 | 2026-10-19 | Multi-line attribute lists; every attribute requires a value (breaking); watch-mode fixes |
| 0.5.0 | 2026-06-11 | Type-safe multi-level extends and doctype |
| 0.4.0 | 2026-04-05 | Templates return strings directly |
| 0.3.0 | 2026-04-05 | Raw blocks (tag!); Emacs mode |
| 0.2.0 | 2026-04-05 | Bare \| emits a space |
| 0.1.0 | 2026-04-05 | Initial release |
License
ISC
