@plinthjs/view
The Plinth view layer: a template compiler and a ViewEngine (the View factory) for named templates, shared data, partials, layouts, stacks and components. Template expressions are plain JavaScript evaluated against the view data.
Install
npm install @plinthjs/viewUsage
import { render, ViewEngine } from '@plinthjs/view'
// One-off compile and render.
render('Hi {{ name }}', { name: 'Ada' }) // 'Hi Ada'
// A registry of named templates (compiled once on registration).
const views = new ViewEngine()
.share({ app: 'Plinth' })
.register('layout', '<title>@yield("title", "Default")</title><body>@yield("content")</body>')
.register('badge', '<span>{{ label }}</span>')
.register(
'home',
`@extends("layout")
@section("title")Home@endsection
@section("content")
<h1>{{ app }}</h1>
@include("badge", { label: user.name })
@endsection`,
)
views.render('home', { user: { name: 'Ada' } })
views.has('home') // true{{ }} HTML-escapes its value, {!! !!} outputs raw HTML, and {{-- --}} is a comment. Wrap a value in HtmlString to mark it as already safe. Unknown @word text passes through unchanged (so test@example.com is safe), and @@if or @{{ x }} escape directive syntax literally.
Control flow
@if (n > 0) positive @elseif (n < 0) negative @else zero @endif @foreach (users as user)
<li class="@class(['row', { first: loop.first }])">{{ loop.iteration }}. {{ user.name }}</li>
@endforeach @forelse (items as item)
<li>{{ item }}</li>
@empty
<p>None</p>
@endforelse @auth Welcome back @else Please sign in @endauth @can('edit', post)
<a href="/edit">Edit</a> @endcan @error("email") <span>{{ $message }}</span> @enderrorAlso supported: @unless, @isset, @empty, @switch, @once, @session, @for, @while, @continue, @break, @env, @production and @verbatim. The loop variable mirrors the conventional $loop (index, iteration, first, last, odd, even, count, remaining, depth, parent). @auth checks the user view variable, @can calls a can(ability, ...args) function from the view data, and @error reads an errors bag.
Forms, data and attributes
<form method="POST">
@csrf {{-- reads the csrf view variable --}} @method('PUT')
<input type="checkbox" @checked(remember) />
<option @selected(value="" ="" ="current)">...</option>
</form>
<script>
const data = @json(payload)
</script>@style, @disabled, @readonly, @required and @js are also available. The same helpers are exported as functions: escapeHtml, classString, styleString, booleanAttribute, jsonEncode, jsEncode and firstError.
Stacks and components
views
.register(
'alert',
'<div{{ attributes.merge({ class: "alert" }) }}><h4>{{ title }}</h4>{{ slot }}</div>',
)
.register(
'page',
'@push("scripts")<script src="/app.js"></script>@endpush' +
'@component("alert", { class: "danger" })@slot("title")Oops@endslot Something broke@endcomponent' +
'@stack("scripts")',
)Components render in an isolated scope with their props, a default slot, named slots, and an AttributeBag as attributes (get, has, merge, class, only, except). Partials also support @includeIf, @includeWhen, @includeUnless, @includeFirst and @each.
Extending the engine
Register extensions before the templates that use them, since templates compile at registration:
const views = new ViewEngine({ env: 'local' }) // @env/@production check this
// `directive`: return JS statements; __append(html) emits, __escape(value) escapes.
views.directive('upper', (expr) => `__append(__escape(String(${expr}).toUpperCase()));`)
// `if`: enables @admin(...) / @elseadmin(...) / @else / @endadmin.
views.if('admin', (user) => (user as { role?: string })?.role === 'admin')
views.register('t', '@upper(name) @admin(user)[admin]@endadmin')