Views
Introduction
Views are how a Plinth application turns data into HTML. The @plinthjs/view package provides a template engine: you write HTML with a few extras ({{ }} for output and @directives for control flow), register the templates by name, and render them with data. Output is escaped by default, templates can inherit from layouts, and reusable pieces can be pulled in as partials or components.
Template expressions are plain JavaScript. Whatever you can write inside if (...) in TypeScript works inside @if (...).
pnpm add @plinthjs/viewRendering a Template
The quickest way to try the engine is the render function, which compiles a template string and renders it once.
import { render } from '@plinthjs/view'
render('Hello {{ name }}', { name: 'Ada' }) // => 'Hello Ada'In an application you register templates with a ViewEngine. Each template is compiled once, when it is registered, and can then be rendered by name as often as you like.
import { ViewEngine } from '@plinthjs/view'
const views = new ViewEngine()
views.register('greeting', '<h1>Hello {{ user.name }}</h1>')
views.has('greeting') // => true
views.render('greeting', { user: { name: 'Ada' } }) // => '<h1>Hello Ada</h1>'Rendering a name that was never registered throws View [nope] is not registered.
Sharing Data With Every View
Use share for values every view needs, such as the application name. Data passed to render wins over shared data with the same key.
views.share({ appName: 'Plinth' })
views.register('footer', '<footer>{{ appName }}</footer>')
views.render('footer') // => '<footer>Plinth</footer>'Rendering From Controllers
A controller returns a Response, so rendering a view means rendering a string and wrapping it in Response.html(). The application scaffolded by create-plinthjs-app (web stack) does this in a small helper at src/support/view.ts. It builds one ViewEngine, registers every .plinth file under src/resources/views using dotted names (auth/login.plinth becomes auth.login), and injects the per-request data every page needs: the CSRF token, the signed-in user, flashed errors and an old() accessor.
import { Response } from '@plinthjs/http'
import { Controller } from './Controller.js'
import { view } from '../../Support/view.js'
import type { Request } from '@plinthjs/http'
export class HomeController extends Controller {
index(request: Request): Response {
return view(request, 'welcome', { title: 'Home' })
}
}In that scaffold, compiled views are cached for the life of the process only when APP_ENV is production. In every other environment the engine is rebuilt on each request, so editing a template shows up on the next refresh. If you build your own helper, the essential part is only this:
return Response.html(views.render('welcome', { user, csrf: token }))Displaying Data
Wrap an expression in double curly braces to print it. The value is HTML-escaped, so user input cannot inject markup.
render('{{ comment }}', { comment: '<script>alert("x")</script>' })
// => '<script>alert("x")</script>'null and undefined print as an empty string, and a variable that does not exist at all also prints nothing instead of throwing.
render('[{{ missing }}] [{{ user.nickname ?? "none" }}]', { user: {} }) // => '[] [none]'Any JavaScript expression is allowed:
render('{{ price * qty }} / {{ items.length }}', { price: 4, qty: 2, items: [1, 2] }) // => '8 / 2'Unescaped Output
Use {!! !!} when a value is already trusted HTML. Never use it for user input.
render('{!! html !!}', { html: '<b>bold</b>' }) // => '<b>bold</b>'You can also mark a string as safe once, in code, by wrapping it in HtmlString. A plain {{ }} then prints it raw.
import { HtmlString } from '@plinthjs/view'
render('{{ badge }}', { badge: new HtmlString('<i>new</i>') }) // => '<i>new</i>'Comments
{{-- --}} is a template comment. It is stripped from the output.
render('a{{-- not rendered --}}b') // => 'ab'Escaping Template Syntax
When a client-side framework needs literal braces, prefix them with @. The @ is removed and the braces are left alone.
render('Hello @{{ name }}', { name: 'x' }) // => 'Hello {{ name }}'To print the name of a directive literally, double the @: @@if outputs @if. For larger blocks, wrap them in @verbatim, and nothing inside is compiled.
render('@verbatim {{ untouched }} @if @endverbatim') // => ' {{ untouched }} @if 'Unknown Directives Pass Through
The engine only acts on directive names it knows. Any other @word is left in the output as text, which means email addresses and handles are safe.
render('Write to test@example.com or @unknown(1)') // => 'Write to test@example.com or @unknown(1)'The flip side is that a misspelled directive such as @endforech is printed into the page rather than rejected on its own. The block it was meant to close is then reported when the template is registered: Unclosed @foreach directive started on line 3; expected @endforeach (found unknown directive @endforech, a typo?).
Rendering JSON
@json prints a value as JSON that is safe inside a script element (<, >, & and ' become unicode escapes). @js prints a JavaScript expression that is also safe inside an HTML attribute.
render('<script>const data = @json(payload)</script>', { payload: { a: '<x>', n: 1 } })
// => '<script>const data = {"a":"<x>","n":1}</script>'
render('<script>const name = @js(name)</script>', { name: "it's" })
// => "<script>const name = 'it's'</script>"Conditionals
@if, @elseif, @else and @endif work like their JavaScript counterparts. @unless is the inverse of @if.
const t = '@if (n > 0)positive@elseif (n < 0)negative@else zero@endif'
render(t, { n: -1 }) // => 'negative'
render('@unless (ok)Not ok@endunless', { ok: false }) // => 'Not ok'Isset and Empty
@isset(x) is true when the expression is neither null nor undefined (so 0 and '' count as set). @empty(x) is true for null, undefined, false, 0, '', empty arrays and empty objects.
render('@isset(a)A@endisset @isset(b)B@endisset', { a: 0 }) // => 'A '
render('@empty(list)none@endempty', { list: [] }) // => 'none'Switch
const t = '@switch(n)@case(1)one@break@case(2)two@break@default other@endswitch'
render(t, { n: 2 }) // => 'two'Text placed between @switch and the first @case is discarded.
Authentication
@auth and @guest look at the truthiness of the user view variable. Pass the signed-in user (or null) as user when you render.
const t = '@auth Welcome back @else Please sign in @endauth'
render(t, { user: { name: 'Ada' } }) // => ' Welcome back '
render(t, { user: null }) // => ' Please sign in '@guest ... @endguest is the reverse. Arguments such as a guard name are accepted but ignored.
Authorization
@can, @cannot and @canany call a function named can that you put in the view data. It receives the ability and any extra arguments, and its boolean result decides whether the block renders. If the view has no can function, every ability is denied.
const can = (ability: string) => ability === 'edit'
render('@can("edit", post)<a href="/edit">Edit</a>@endcan', { post: {}, can })
// => '<a href="/edit">Edit</a>'
render('@cannot("delete", post)Read only@endcannot', { post: {}, can })
// => 'Read only'
render('@canany(["edit", "delete"], post)Manage@endcanany', { post: {}, can })
// => 'Manage'Wire can to your authorization layer in the helper that renders views, so templates never see how permissions are decided.
Environment
@env('local') renders only when the engine's environment matches; it also accepts an array of names. @production is shorthand for the production environment. The environment is the env option of ViewEngine, which defaults to the APP_ENV variable and then to production.
const views = new ViewEngine({ env: 'local' })
views.register(
'x',
"@env('local')dev tools@endenv @env(['staging', 'local'])x@endenv @production live@endproduction",
)
views.render('x') // => 'dev tools x 'Flash Data
@session('key') renders its body when the session view variable has a non-null value for that key, and exposes the value as $value. The session variable can be a function, a Map or any object with a get method, or a plain object.
render('@session("status")<p>{{ $value }}</p>@endsession', { session: { status: 'Saved' } })
// => '<p>Saved</p>'Validation Errors
@error('field') renders its body when the errors view variable has a message for the field, and exposes the first message as $message. errors can be a validation ErrorBag or a plain object of strings or string arrays.
const t = '@error("email")<span>{{ $message }}</span>@enderror'
render(t, { errors: { email: ['The email field is required.'] } })
// => '<span>The email field is required.</span>'Once
@once renders its body a single time per render, even when it sits inside a loop or in a partial included many times.
views.register(
'o',
'@foreach (xs as x)@once<script src="/a.js"></script>@endonce{{ x }}@endforeach',
)
views.render('o', { xs: [1, 2] }) // => '<script src="/a.js"></script>12'Loops
Besides @foreach, the engine supports @for and @while, using the same syntax as the JavaScript statements.
render('@for (let i = 0; i < 3; i++){{ i }}@endfor') // => '012'Foreach
@foreach (items as item) iterates an array, any iterable, or the values of a plain object. Use key => value to get keys from an object or a Map.
render('@foreach (users as user)<li>{{ user }}</li>@endforeach', { users: ['Ada', 'Lin'] })
// => '<li>Ada</li><li>Lin</li>'
render('@foreach (prices as name => price){{ name }}={{ price }};@endforeach', {
prices: { a: 1, b: 2 },
})
// => 'a=1;b=2;'A null or undefined collection simply iterates zero times.
Forelse
@forelse is a loop with an @empty branch for when there is nothing to iterate.
render('@forelse (items as i)<li>{{ i }}</li>@empty<p>None</p>@endforelse', { items: [] })
// => '<p>None</p>'The Loop Variable
Inside @foreach and @forelse a variable named loop describes the current iteration.
| Property | Meaning |
|---|---|
index | Zero-based index of the iteration |
iteration | One-based number of the iteration |
first, last | Whether this is the first or last iteration |
odd, even | Whether the iteration number is odd or even |
count | Total number of items |
remaining | Iterations left after this one |
depth | Nesting level, starting at 1 |
parent | The enclosing loop variable, in a nested loop |
const t =
'@foreach (users as user)<li class="@class([\'row\', { first: loop.first }])">{{ loop.iteration }}/{{ loop.count }} {{ user }}</li>@endforeach'
render(t, { users: ['a', 'b'] })
// => '<li class="row first">1/2 a</li><li class="row">2/2 b</li>'In a nested loop, loop.parent reaches the outer iteration, for example loop.parent.iteration.
Continue and Break
@continue and @break skip an iteration or leave the loop. Pass a condition to make them conditional, or a number to jump out of that many nested loops.
const t = '@foreach (xs as x)@continue(x === 2)@break(x === 4){{ x }}@endforeach'
render(t, { xs: [1, 2, 3, 4, 5] }) // => '13'Attribute Helpers
These directives print a fragment, not a whole attribute, so you place them where you need them.
@class builds a class list. A string is always kept; in an object, the key is kept when its value is truthy. @style does the same for inline declarations.
render(
"<p class=\"@class(['a', { b: on, c: off }])\" style=\"@style(['color: red', { 'top: 0': on }])\">",
{
on: true,
off: false,
},
)
// => '<p class="a b" style="color: red; top: 0;">'@checked, @selected, @disabled, @readonly and @required print the attribute name when the condition is truthy and nothing otherwise.
render('<input type="checkbox" @checked(remember) @disabled(locked)>', {
remember: true,
locked: false,
})
// => '<input type="checkbox" checked >'Forms
@csrf prints a hidden _token input using the csrf view variable, and @method prints a hidden _method input so an HTML form can submit a PUT, PATCH or DELETE. See CSRF Protection for how the token is verified.
render('<form method="POST">@csrf @method("PUT")</form>', { csrf: 'abc123' })
// => '<form method="POST"><input type="hidden" name="_token" value="abc123"> <input type="hidden" name="_method" value="PUT"></form>'Layouts and Sections
Layouts let many pages share one skeleton. A layout declares holes with @yield, and a child template fills them with @section.
const views = new ViewEngine()
.share({ app: 'Plinth' })
.register('layout', '<title>@yield("title", "Default")</title><body>@yield("content")</body>')
.register(
'home',
`@extends("layout")
@section("title")Home@endsection
@section("content")<h1>{{ app }}</h1>@endsection`,
)
views.render('home')
// => '<title>Home</title><body><h1>Plinth</h1></body>'The second argument of @yield is the fallback used when a child defines no such section. A section with only a short string can be written inline: @section('title', 'Home') (the value is escaped).
Layouts can nest: a layout may itself @extends another. In a layout, end a section with @show to render it immediately and still let children override it. In a child, @parent prints the content the parent gave the section.
views.register('base', '@section("sidebar")base@show')
views.register('page', '@extends("base")@section("sidebar")@parent+page@endsection')
views.render('page') // => 'base+page'Use @hasSection('name') and @sectionMissing('name') to branch on whether a section has content. Both close with @endif.
views.register('hs', '@hasSection("title")has title@endif @sectionMissing("footer")no footer@endif')
views.render('hs') // => ' no footer'Including Partials
@include('name', data) renders another registered view inside the current one. The partial sees the parent's variables, plus anything in the second argument.
views.register('badge', '<span>{{ label }}</span>')
views.register('card', '<div>@include("badge", { label: user.name })</div>')
views.render('card', { user: { name: 'Ada' } }) // => '<div><span>Ada</span></div>'Variants cover the common conditions:
@includeIf('name')renders only if the view exists.@includeWhen(condition, 'name', data)and@includeUnless(condition, 'name', data)include based on a condition.@includeFirst(['a', 'b'], data)renders the first view in the list that exists, and throws if none do.@each('view', items, 'itemName', 'emptyView')rendersviewonce per item, passing the item underitemNameand its key askey. The optional last argument is a view to render whenitemsis empty, or a string starting withraw|to print literal text instead.
views.register('row', '<li>{{ it }}-{{ key }}</li>')
views.register('list', '@each("row", things, "it", "raw|<li>none</li>")')
views.render('list', { things: ['x', 'y'] }) // => '<li>x-0</li><li>y-1</li>'
views.render('list', { things: [] }) // => '<li>none</li>'Stacks
A stack collects content from anywhere in the render tree (partials, children, components) and prints it in one place. This is how a nested view adds a script to the bottom of the page.
views.register('shell', '<body>@yield("content")@stack("scripts")</body>')
views.register(
'page2',
'@extends("shell")@section("content")Hi@push("scripts")<script src="/a.js"></script>@endpush@endsection',
)
views.render('page2') // => '<body>Hi<script src="/a.js"></script></body>'@prepend adds to the front of a stack instead of the end. @pushOnce('name', 'key') and @prependOnce add content only the first time a given key is seen, closing with @endPushOnce and @endPrependOnce. This keeps a library script from being added by every component that needs it.
views.register(
's',
'@pushOnce("js", "lib")A@endPushOnce@pushOnce("js", "lib")B@endPushOnce[@stack("js")]',
)
views.render('s') // => '[A]'Components
A component is a registered view rendered with props and slots. Open one with @component('name', props); the body becomes the default slot, and @slot('name') blocks become named slots. Inside the component, the props, slot and the named slots are all plain variables.
views.register(
'alert',
'<div{{ attributes.merge({ class: "alert" }) }}><h4>{{ title }}</h4>{{ slot }}</div>',
)
views.register(
'page3',
'@component("alert", { class: "danger", id: "a1" })@slot("title")Oops@endslot Something broke@endcomponent',
)
views.render('page3')
// => '<div class="alert danger" id="a1"><h4>Oops</h4> Something broke</div>'A component renders in an isolated scope: it receives its props and slots, plus data you shared with share, but not the variables of the template that used it. Slot content is already HTML, so it is printed unescaped; escape any user data inside the slot as usual.
The Attribute Bag
Every component receives an AttributeBag named attributes, holding every prop passed to @component. Printing it renders the pairs as escaped name="value" text (with a leading space), so you put it directly after the tag name.
| Method | Result |
|---|---|
attributes.get(key, fallback) | One value |
attributes.has(key) | Whether the key is present |
attributes.all() | A plain object copy |
attributes.merge(defaults) | Defaults under the caller's values; class and style are concatenated, defaults first |
attributes.class([...]) | Merge a conditional class list, like @class |
attributes.only(...keys) | A bag with just those keys |
attributes.except(...keys) | A bag without those keys |
By default the bag contains every prop. Declare the props a component consumes itself with views.props('btn', ['label']), and only the other (undeclared) attributes land in attributes. Without a declaration, use except to keep them out of the markup:
views.register(
'btn',
'<button{{ attributes.except("label").merge({ type: "button", class: "btn" }) }}>{{ label }}</button>',
)
views.register('p4', '@component("btn", { label: "Save", class: "primary" })@endcomponent')
views.render('p4') // => '<button type="button" class="btn primary">Save</button>'You can also build a bag yourself:
import { AttributeBag } from '@plinthjs/view'
String(new AttributeBag({ id: 'a', disabled: true, hidden: false })) // => ' id="a" disabled'true prints a bare attribute name, and false, null and undefined omit the attribute.
Custom Directives
Register your own directive with directive. The handler receives the raw text between the directive's parentheses and returns JavaScript statements that are spliced into the compiled template. Inside them, __append(html) writes output and __escape(value) escapes a value.
const views = new ViewEngine()
views.directive('upper', (expression) => `__append(__escape(String(${expression}).toUpperCase()));`)
views.register('t', '@upper(name)')
views.render('t', { name: 'ada' }) // => 'ADA'Because templates compile when they are registered, register directives first. A custom directive takes precedence over a built-in one with the same name. Names must be a single word (letters, digits, underscore).
Custom Conditionals
if registers a predicate and enables a whole family of directives from one name: @admin(...), @elseadmin(...), @unlessadmin(...), plain @else and @endadmin.
views.if('admin', (user) => (user as { role?: string } | undefined)?.role === 'admin')
views.register('who', '@admin(user)[admin]@elseadmin(other)[other]@else[nobody]@endadmin')
views.render('who', { user: { role: 'admin' } }) // => '[admin]'
views.render('who', { user: {} }) // => '[nobody]'Using the Vite Assets
To load your compiled CSS and JavaScript from a layout, share a Vite instance and print its tags unescaped. See Vite.
WARNING
Templates are trusted author code. They are compiled with the JavaScript Function constructor and have access to the view data and to globals. Only data is escaped, so never build a template string from user input.