Layouts and Slots
+layout.ets files wrap pages. A page's layouts are every +layout from its own folder up to pb_pages/, applied innermost first. A folder may have one layout, written as +layout.ets (or +layout.tsx, see TSX). A layout can't be Markdown: +layout.md is an error at startup.
pb_pages/
+layout.ets # applied last (outermost)
products/
+layout.ets # applied first
[id].ets
For /products/123, [id].ets renders, then products/+layout.ets wraps it, then +layout.ets wraps that.
slot()
In a layout, slot() returns the content being wrapped: the page, or the inner layout.
<!-- pb_pages/+layout.ets -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Application</title>
</head>
<body>
<main>
<%- slot() %>
</main>
<footer>© <%= new Date().getFullYear() %> My Application</footer>
</body>
</html>
<%- slot %> without parentheses prints the same content, so 0.x layouts that wrote it still work.
Named slots
A page (or an inner layout) defines a named slot with slot(name, fn). fn's output is captured and nothing is output in place. A layout reads it with slot(name), which returns '' if it isn't defined.
<!-- pb_pages/products/[id].ets -->
<% slot('title', () => { %><%= data.product.getString('name') %><% }) %>
<h1><%= data.product.getString('name') %></h1>
<!-- pb_pages/+layout.ets -->
<html>
<head><title><%- slot('title') || 'My shop' %></title></head>
<body><%- slot() %></body>
</html>
- Named slots defined by the page or by any inner layout are visible to every outer layout.
- Defining the same name again replaces it. Inside the new definition's
fn,slot(name)still returns the previous content, so a layout can wrap it:
<!-- pb_pages/docs/+layout.ets -->
<% slot('title', () => { %>Docs: <%- slot('title') %><% }) %>
<main><%- slot() %></main>
Data in layouts
Layouts render after the page, with the same ctx. Everything middleware, the page's code and the page put on ctx.data or ctx.meta is there.
When layouts are skipped
- When the response isn't HTML (a handler set another
Content-Type). - When a handler or middleware sent the response itself (
ctx.res.json,ctx.res.html,ctx.res.redirect, ...). - For endpoints, which have no template.
- After
ctx.res.layout(false), called from middleware, the page's code or the page itself. - With the Datastar add-on, for requests that carry
Datastar-Request: true.
To serve HTML fragments without the site layout, call ctx.res.layout(false), put the layout in a group ((site)/+layout.ets) and the fragments outside it, or send them with ctx.res.html().
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.