Loading Data in Pages
You can load data right in a template, or in a .ts file of the same name next to it.
Inline data loading
The simplest way is a <% %> block at the top of your template:
<%
const products = ctx.app.findRecordsByFilter('products', 'active = true', 'name', 100)
%>
<h1>Products</h1>
<% for (const product of products) { %>
<div class="product">
<h2><%= product.getString('name') %></h2>
</div>
<% } %>
Server script blocks
For better formatting support in editors, you can write <script server> instead of <% %>. They mean the same thing:
<script server>
const products = ctx.app.findRecordsByFilter('products', 'active = true', 'name', 100)
const categories = ctx.app.findAllRecords('categories')
</script>
<h1>Products by Category</h1>
<% for (const category of categories) { %>
<h2><%= category.getString('name') %></h2>
<% } %>
Page code
A .ts file beside a template, with the same name, is that page's code. It keeps data loading and form handling out of the template: about.ts goes with about.ets, index.ts with index.ets, [id].ts with [id].ets.
// pb_pages/products/[id].ts
module.exports = {
load(ctx) {
ctx.data.product = ctx.app.findRecordById('products', ctx.params.id)
},
post(ctx) {
const { qty } = ctx.req.body()
// ...
return ctx.res.redirect(`/products/${ctx.params.id}`, { flash: 'Added to cart' })
},
}
<!-- pb_pages/products/[id].ets -->
<h1><%= data.product.getString('name') %></h1>
<% const flash = ctx.flash() %>
<% if (flash) { %><p><%= flash %></p><% } %>
Exports
Page code exports any of load, get, post, put, patch and delete.
loadruns first, for every method.- Then the handler for the request method runs, if there is one.
- Then the page renders.
A handler can set fields on ctx.data, or return a plain object. A returned object is shallow-assigned into ctx.data (Object.assign); there is no deep merge.
module.exports = {
load(ctx) {
return { departments: ctx.app.findAllRecords('departments') }
},
get(ctx) {
ctx.data.mode = 'view'
},
}
If a handler sends a response (ctx.res.redirect, json, html, text, file, sse), the page doesn't render.
Async loading
load and the method handlers can be async. Pages waits for them before it renders. Every Go function has an
.async twin that does its work outside the JS VM, so other requests keep running while it waits:
// pb_pages/dashboard.ts, beside dashboard.ets
module.exports = {
async load(ctx) {
const [orders, users] = await Promise.all([
ctx.app.countRecords.async('orders'),
ctx.app.countRecords.async('users'),
])
return { orders, users }
},
}
What an async handler returns is used just like a returned object, and an error it throws (or a rejected promise)
fails the request like any other error. You can also await right in a template: see ETS and
JSX.
Code several pages share
Each page has its own code file. Put code that several pages share in a _private/ module and require it, or in a +middleware.ts when a whole section needs it:
// pb_pages/products/[id].ts
const { reviewsFor } = require('./_private/reviews')
module.exports = {
load(ctx) {
return { reviews: reviewsFor(ctx.app, ctx.params.id) }
},
}
Methods without a handler
Every handler is optional. A page renders for any method, like PHP, so a template can handle a form on its own:
<!-- pb_pages/contact.ets, no contact.ts -->
<% if (ctx.req.method === 'POST') { %>
<p>Thanks, <%= ctx.req.body().name %>!</p>
<% } else { %>
<form method="post"><input name="name" /><button>Send</button></form>
<% } %>
A post (or put, ...) handler in the page's code is the tidier place for form logic as a page grows, but you don't
need one. Only endpoints, which have nothing to render, answer 405 for a method they have no
handler for.
Example: a contact form
// pb_pages/contact.ts
module.exports = {
load(ctx) {
return { departments: ctx.app.findAllRecords('departments') }
},
post(ctx) {
const { email, message, department } = ctx.req.body()
try {
const record = new Record(ctx.app.findCollectionByNameOrId('messages'))
record.set('email', email)
record.set('message', message)
record.set('department', department)
ctx.app.save(record)
} catch (e) {
return { error: 'Failed to send message', values: { email, message, department } }
}
return ctx.res.redirect('/contact', { flash: 'Thanks, we got your message.' })
},
}
<!-- pb_pages/contact.ets -->
<% const flash = ctx.flash() %>
<% if (flash) { %><p><%= flash %></p><% } %>
<% if (data.error) { %><mark><%= data.error %></mark><% } %>
<form method="post">
<input name="email" type="email" value="<%= data.values?.email %>" />
<select name="department">
<% for (const d of data.departments) { %>
<option value="<%= d.id %>"><%= d.getString('name') %></option>
<% } %>
</select>
<textarea name="message"><%= data.values?.message %></textarea>
<button type="submit">Send</button>
</form>
Pages without a template
A .ts file with no template of the same name serves its URL from code: an endpoint. Use one for a
page you'd rather build in code, or for a URL that only acts and redirects:
// pb_pages/logout.ts
module.exports = {
post(ctx) {
ctx.session.signOut()
return ctx.res.redirect('/')
},
}
// pb_pages/hello.ts
module.exports = {
get(ctx) {
return ctx.res.html(`<h1>Hello ${ctx.auth ? ctx.auth.getString('name') : 'there'}</h1>`)
},
}
- With no template to render, each handler must send a response; returning without one is a 500.
- Methods without a handler answer
405,GETincluded:/logoutabove only takesPOST. - Folder middleware runs; layouts don't, so wrap HTML yourself (or render a partial with
ctx.include). - Errors are JSON, or your
+error.etspage when the request asks for HTML first (a browser opening the URL).
Middleware or page code?
- Only the page's own
.tsruns. - Every
+middleware.tsfrompb_pages/down to the route's folder runs, root first.
Use middleware for data or checks that a whole section of the site shares.
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.