Building an app
Views and helpers
Views are plain PHP templates. This page covers views, layouts, elements and blocks, how output is escaped, the global template helpers, the HTML and form helper, CSRF fields, widgets and Vite assets. It assumes you know how an action renders (Routing and controllers).
Contents
#- Views
- Escaping
- Layouts
- Elements and blocks
- Template helpers
- The HTML helper
- Forms and CSRF
- Widgets
- Vite
Views
#A view is app/Views/<controller>/<action>.tpl.php. An action that sets $this->autoRender = true and returns nothing renders its view inside the controller's layout. The controller's public properties become the view's variables:
<?php
// app/Controllers/ArticleController.php
namespace App\Controllers;
use Taphra\SafeString;
class ArticleController extends AppController
{
public $helpers = ['Html']; // $html in the views
public $layout = 'site'; // app/Layouts/site.lyt.php
public function show(): void
{
$this->viewTitle = 'Fish & Chips';
$this->title = 'Fish & Chips <3';
$this->article = ['body' => '<b>not bold</b>', 'tags' => ['food', 'uk']];
$this->notice = new SafeString('<em>Trusted markup</em>');
$this->autoRender = true;
}
}<!-- app/Views/article/show.tpl.php -->
<h1><?= $title ?></h1>
<p><?= e($title) ?></p>
<div><?= e($article['body']) ?></div>
<p><?= $notice ?></p>
<?php $this->element('tag-list', ['tags' => $article['tags']]) ?>
<?= $html->anchor(['href' => '/articles?q=' . rawurlencode('a&b'), 'text' => 'Search "a&b"']) ?>To render something else, call render() from the action:
// in a controller action
$this->render(); // the action's view in $this->layout
$this->render('list'); // app/Views/<controller>/list.tpl.php
$this->render('list', 'minimal'); // with app/Layouts/minimal.lyt.php
$html = $this->render('list', null, false); // return the HTML instead of printing it
$this->renderPartial('_row', ['row' => $row]); // no layout (for HTMX and fragments)A view name in camelCase also finds a snake_case file: the action showLogin renders show_login.tpl.php when showLogin.tpl.php does not exist.
Escaping
#Inside a view the rules are:
- Every top-level string variable is HTML-escaped once before the template runs, so
<?= $title ?>printsFish & Chips <3. e()escapes a value for HTML. It recognises a variable the view already escaped and does not escape it again, so<?= e($title) ?>prints the same thing. Usee()everywhere: then you never have to remember which values were escaped.- Strings inside arrays and objects (
$article['body'],$row->name) are not escaped for you: print them withe(). - A
Taphra\SafeStringis printed as it is. Use it only for markup you built or cleaned yourself; clean user-supplied rich text withTaphra\HtmlSanitizer::clean($html)first (it needsext-dom). - Escaping is for HTML text and quoted attribute values. For JavaScript use
json_encode(), for a URL componentrawurlencode().
Do not call htmlspecialchars() on a view variable: it escapes the already-escaped value a second time (&amp;). e() does not.
Layouts
#A layout wraps the view. It is app/Layouts/<name>.lyt.php, chosen by the controller's $layout property (default in the skeleton). Inside it, $this is the view object and holds:
| Property | Content |
|---|---|
$this->viewContent |
the rendered view |
$this->viewTitle |
the controller's $viewTitle (not escaped) |
$this->viewStyleSheets, $this->viewScripts |
tags added with $this->addCss() and $this->addJS() in the view |
$this->viewLang, $this->viewCharSet, $this->viewDocType |
page settings (en-US, UTF-8, HTML5 by default) |
$this->viewVars |
the controller's properties, not escaped |
<!-- app/Layouts/site.lyt.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= e($this->viewTitle) ?></title>
<?= $this->viewStyleSheets ?>
</head>
<body>
<main><?= $this->viewContent ?></main>
<?= $this->viewScripts ?>
</body>
</html>Layout values are not escaped for you, so the title goes through e().
Elements and blocks
#An element is a reusable fragment in app/Elements/<name>.elm.php. From a view, $this->element('name', $params) prints it (pass true as the fourth argument to get the HTML back instead). The parameters become its variables, escaped like a view's; the controller's properties are in $actionvars.
A view variable passed on to an element is already escaped, and the element does not escape it again: with $this->element('card', ['name' => $name]), <?= $name ?> and <?= e($name) ?> in the element print O'Brien & Co for O'Brien & Co, once. The same holds for an element that passes it on to another element. Pass any other string as it is, not through e() or htmlspecialchars() (the element escapes it); a SafeString stays as it is, and arrays and objects are passed unchanged, so print the strings inside them with e().
<!-- app/Elements/tag-list.elm.php -->
<ul class="tags">
<?php foreach ($tags as $tag): ?>
<li><?= e($tag) ?></li>
<?php endforeach; ?>
</ul>A controller renders an element directly with $this->renderElement('tag-list', ['tags' => $tags]).
Blocks let a view hand content to the layout. The view captures it, the layout prints it:
<!-- in a view -->
<?php $this->startBlock('head') ?>
<link rel="preload" href="/fonts/body.woff2" as="font" crossorigin>
<?php $this->endBlock('head') ?>
<!-- in the layout -->
<?php if (isset($this->blocks['head'])) $this->block('head'); ?>Template helpers
#These global functions work in views and anywhere else:
| Function | Returns |
|---|---|
e($value) |
the value escaped for HTML (once; a SafeString as is; arrays and objects as JSON) |
old($field, $default = '') |
the field's value from the last failed form submission, escaped, else $default escaped |
error($field, $wrap = '%s') |
the field's first validation error, placed in $wrap, or '' |
url($path = '') |
an absolute URL from app.base_url (Configuration) |
asset($path) |
an absolute URL under app.asset_url, else under url() |
classes($map) |
a class list: classes(['btn', 'active' => $isActive]) |
when($condition, $value, $else = '') |
$value or $else as a string |
config($key, $default = null) |
Config::get() |
__($key, $replace = []) |
a translation (Localisation) |
dump(...), dd(...), pr($value), vd(...) |
debug output (dd() stops the request) |
echo e('Tom & "Jerry"'), "\n"; // Tom & "Jerry"
echo classes(['btn', 'btn-primary' => true, 'disabled' => false]), "\n"; // btn btn-primary
echo when(false, 'checked', 'unchecked'), "\n"; // unchecked
echo e(new \Taphra\SafeString('<b>ok</b>')), "\n"; // <b>ok</b>Each global is defined only when no function of that name exists yet, so your app (or a library such as symfony/var-dumper, which has its own dump() and dd()) can define its own. Taphra\Helpers has the same helpers as static methods (Helpers::e(), Helpers::old(), Helpers::error(), Helpers::url(), Helpers::asset(), Helpers::classes(), Helpers::when(), Helpers::dump(), Helpers::dd(), Helpers::pr(), Helpers::vd()); the framework calls those, and so can code that must get Taphra's behaviour whatever the globals are.
use Taphra\Helpers;
echo Helpers::e('<script>'), "\n"; // <script>
echo Helpers::classes(['a', 'b' => 1]), "\n"; // a bThe HTML helper
#List Html in the controller's $helpers (public $helpers = ['Html'];) and views get $html, a Taphra\HtmlHelper. Its builders escape attribute values, link text, labels, option labels and textarea content; a SafeString passed as text is inserted as it is.
<!-- in a view -->
<?= $html->anchor(['href' => '/posts/1', 'text' => 'Read "more"']) ?>
<?= $html->anchor(['href' => '/', 'text' => new \Taphra\SafeString('<svg aria-hidden="true"></svg> Home')]) ?>
<?= $html->image('/img/logo.png', 'Logo', ['width' => 120]) ?>
<?= $html->h(2, 'Latest & greatest') ?>
<?= $html->ul(['First', 'Second']) ?>
<?= $html->tag('span', e($note), ['class' => 'note']) ?>tag($name, $content, $attributes), div(), span() and p() insert their content as HTML (escape untrusted text with e() first); h(), anchor(), label(), button(), submit(), ul() and ol() escape their text. breadcrumb($items) and pagination($page, $url) build navigation; pagination() takes the PaginatedResult of a DataStore query (DataStores).
Forms and CSRF
#Controllers that extend the skeleton's AppController reject every request that is not GET, HEAD or OPTIONS unless it carries the session's CSRF token (403 otherwise). Put the token in each form:
<!-- app/Views/post/edit.tpl.php -->
<form method="post" action="/posts/<?= e($post['id']) ?>/update">
<?= $this->csrf() ?>
<input name="title" value="<?= old('title', $post['title']) ?>">
<?= error('title', '<p class="error">%s</p>') ?>
<button>Save</button>
</form>$this->csrf() prints <input type="hidden" name="_csrf_token" value="...">. JavaScript clients send the same token in an X-CSRF-Token header instead; print it where your script can read it, for example <meta name="csrf-token" content="<?= e(\Taphra\Security::generateCsrfToken()) ?>">.
The HTML helper builds the same form; formOpen() adds the token field, and fields fill themselves from old input after a failed validation, then from data you bind:
<!-- app/Views/post/edit.tpl.php -->
<?php $html->setErrorTemplate('<p class="error">%s</p>'); ?>
<?= $html->bind($post)->formOpen('/posts/' . $post['id'] . '/update') ?>
<?= $html->label('title', 'Title') ?>
<?= $html->text('title', null, ['id' => 'title', 'required' => true]) ?>
<?= $html->select(['name' => 'status'], ['draft' => 'Draft', 'published' => 'Published']) ?>
<?= $html->textarea('body', null, ['rows' => 8]) ?>
<?= $html->checkbox('featured') ?>
<?= $html->submit('Save') ?>
<?= $html->formClose() ?>bind() takes an array (call toArray() on a DataStore row). A field with a validation error gets the is-invalid class and, once you set an error template, the message after it. password() and file() are never filled. Validation, old() and error() are covered in Requests and validation.
Widgets
#A widget is a server-rendered component: a class in app/Widgets/ and a template in app/Widgets/<Name>/View/<name>.tpl.php.
<?php
// app/Widgets/StatsWidget.php
namespace App\Widgets;
use Taphra\Widget;
class StatsWidget extends Widget
{
public function data(): array
{
return ['total' => $this->params['total'] ?? 0];
}
}<?php // app/Widgets/Stats/View/stats.tpl.php ?>
<p class="stats"><?= e($total) ?> orders</p>use Taphra\Widget;
echo Widget::make('Stats', ['total' => 42], false), "\n";
// <p class="stats">42 orders</p>
echo Widget::make('Stats', ['total' => 42]), "\n";
// the same, wrapped in <div data-component="Stats" data-props='{"total":42}'>
echo Widget::mount('UserProfile', ['userId' => 1]), "\n";
// <div data-component="UserProfile" data-props='{"userId":1}'></div>Widget::make($name, $params = [], $withBridge = true) renders the widget; with the bridge (the default) the HTML is wrapped in an element carrying data-component and the widget's data() as JSON in data-props (HTML-escaped in the attribute; el.dataset.props gives the JSON back), for Alpine.js or HTMX to pick up. Widget template variables are not escaped for you: use e(). Define TPHR_WIDGET_PATH to look for widget templates in a second, shared folder.
Widget::mount($component, $props = [], $bundle = '') prints only an empty mount point for a JavaScript component (React, Vue, Svelte). A few lines in your bundle hydrate them:
document.querySelectorAll('[data-component]').forEach((el) => {
const load = el.dataset.bundle
? import(`/js/bundles/${el.dataset.bundle}.js`)
: Promise.resolve(window.__TAPHRA_COMPONENTS__);
load.then((components) => {
const Component = components[el.dataset.component];
if (Component) {
ReactDOM.createRoot(el).render(React.createElement(Component, JSON.parse(el.dataset.props)));
}
});
});window.__TAPHRA_COMPONENTS__ is the object your bundle fills with its components.
Vite
#Taphra\Vite\ViteHelper prints the tags for a Vite entry point: the Vite dev server's URLs in development, the hashed files from the build manifest otherwise.
use Taphra\Vite\ViteHelper;
ViteHelper::configure([
'public_path' => '/dist', // URL prefix of the built files
'dev_url' => 'http://localhost:5173', // the Vite dev server
'dev_mode' => true, // leave out to follow the app mode
]);
echo ViteHelper::tags('src/main.js');
// <script type="module" src="http://localhost:5173/@vite/client"></script>
// <script type="module" src="http://localhost:5173/src/main.js"></script>In a layout, <?= ViteHelper::tags('src/main.js') ?> goes in the <head>; with @vitejs/plugin-react, put <?= ViteHelper::reactRefresh() ?> before it. ViteHelper::asset('src/images/logo.png') gives one file's URL. Outside development the helper reads manifest.json (Vite 5 writes it to .vite/manifest.json) from build_dir, or by default from public/dist next to app/ or app/Static/dist.