Documentation menu

Templates

A php-via page has two layers. The outer document carries the doctype, the head, the scripts that connect the page and your site's chrome. The view is the part that renders again on every update. The outer document is either a shell, a plain HTML file with placeholders, or a template that renders the whole document. The view is a PHP callable that returns HTML, or a template that a template engine renders. php-via has an adapter for Twig, which you install yourself.

Shells and views

Shell: shell.html

A static HTML file set with withShellTemplate(). php-via replaces its {{ placeholder }} tokens with plain string replacement, not Twig. The shell goes out once per page load and never over SSE. Use it for the outer chrome: doctype, nav, footer, stylesheets.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {{ via_head }}
    {{ head_content }}
</head>
<body>
    {{ content }}
    {{ foot_content }}
    {{ via_foot }}
</body>
</html>

View: callable or template

The page content, set with $c->view() and rendered again on every update. A callable needs nothing else; a template name needs a template engine.

// PHP callable: no engine needed
$c->view(function () use ($count): string {
    return '<p id="count">' . $count->int() . '</p>';
});

// Twig template: signals and actions come in by name
$c->view('counter.html.twig');

Template engines

A template view, $c->view('page.html.twig'), and $c->render() go through the TemplateEngine registered with Config::withTemplateEngine(). Without one, views are callables, and a template view, render() or $app->getTwig() throws a LogicException that names the fix.

Twig

twig/twig does not come with php-via. Install it, then point php-via at the template directory:

composer require twig/twig
$app = new Via(
    (new Config())
        ->withTemplateDir(__DIR__ . '/templates')    // Twig views
        ->withTwigCacheDir(__DIR__ . '/var/twig')    // optional: compiled templates on disk
        ->withShellTemplate(__DIR__ . '/shell.html') // optional: your own shell
);

withTemplateDir($dir) is short for withTemplateEngine(new TwigEngine($dir)), and new Via() throws when Twig is not installed. Templates are autoescaped as HTML and strict about undefined variables. Besides Twig's own, they get the functions bind(), dump(), via_head() and via_foot(), and the global basePath.

$app->getTwig() returns the Twig\Environment, for extensions, globals and templates held as strings. Register extensions right after new Via(), before the first render.

$app->getTwig()->addExtension(new MyExtension());
$html = $app->getTwig()->createTemplate('<p>{{ greeting }}</p>')->render(['greeting' => 'Hello']);

Another engine

Any engine works behind the Rendering\TemplateEngine interface: render() gets the template name, the data and, when supportsBlocks() says so, a block name. via_head and via_foot arrive in the data as Rendering\Html objects. Print them unescaped: an autoescaping engine marks Html as safe markup.

use Mbolli\PhpVia\Rendering\TemplateEngine;

final class PhpTemplates implements TemplateEngine {
    public function __construct(private string $dir) {}

    public function render(string $template, array $data, ?string $block = null): string {
        extract($data);
        ob_start();
        require $this->dir . '/' . $template;

        return (string) ob_get_clean();
    }

    public function supportsBlocks(): bool {
        return false; // view(..., block:) then throws
    }
}

$config->withTemplateEngine(new PhpTemplates(__DIR__ . '/views'));

The page bootstrap: via_head and via_foot

Every page needs a few tags to connect to php-via: the via_ctx signal that names its context, the import map when there is one, the SSE connect with its reconnect, the beacon that closes the context when the tab goes, and Datastar. via_head writes the first four and belongs right after <meta charset>; via_foot writes the Datastar module script, loaded from Config::getDatastarUrl(), and belongs before </body>.

  • In a shell: {{ via_head }} and {{ via_foot }}.
  • In a Twig layout: {{ via_head() }} and {{ via_foot() }}.
  • In a callable that returns a whole document: $c->viaHead() and $c->viaFoot().

Every tag carries the page request's CSP nonce when middleware sets one (see Content-Security-Policy). A page that loads its own Datastar bundle leaves via_foot out.

php-via logs a warning once per shell, and once per route whose view renders a whole document, in two cases: the page has no via_head, so it never opens its stream, or it loads a Datastar script of its own next to an import map, which starts a second Datastar engine. Dev mode also warns about via_head without any Datastar script and about a page with more than one import map.

Shells

Without withShellTemplate(), php-via uses its default shell, which loads /via.css and, in dev mode, shows a Live Signals panel. Your own shell replaces it for every page, and $c->setShellTemplate() for one page. These placeholders are filled:

  • {{ via_head }} and {{ via_foot }}: the bootstrap above
  • {{ via_html_attrs }}: the attributes of <html>, data-nonce under a nonce (see Content-Security-Policy)
  • {{ content }}: the rendered view
  • {{ head_content }} and {{ foot_content }}: what appendToHead() and appendToFoot() added, plus the seed of the signals' initial values
  • {{ base_path }}: the base path from withBasePath(), ending in /
  • {{ context_id }}: the context's id
  • {{ dev_sidebar }}: the Live Signals panel in dev mode, empty otherwise
  • {{ name }} and {{ name.id }}: a signal's JSON value (HTML-escaped) and its id, where name is the name passed to signal()

Twig tags in a shell come out as text. A worker reads each shell once; in dev mode it reads an edited shell again, and outside dev mode a changed shell needs a reload of the server.

Layouts that render the whole document

Instead of a shell, a Twig base template can define the whole document, and page templates extend it. When a view renders an <html> document, php-via skips the shell and completes the document instead.

{# templates/base.html.twig #}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {{ via_head() }}
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <nav>...shared nav...</nav>
    <main>{% block content %}{% endblock %}</main>
    {{ via_foot() }}
</body>
</html>
{# templates/my-page.html.twig #}
{% extends "base.html.twig" %}

{% block title %}My App{% endblock %}

{% block content %}
    <h1>Hello</h1>
{% endblock %}

On the page load php-via adds the seed of the signals' initial values right after via_head's first tag, so expressions have their values before the stream opens; a value the layout sets in its own data-signals wins. It adds what appendToHead() and appendToFoot() collected before the first </head> and the last </body>, on the page load and on every update, unless the exact markup is already there.

The whole template renders again on every update, unlike a shell, which goes out once. Send only the part that changes with block:. A callable view can return a whole document too:

$c->view(fn (): string => '<!DOCTYPE html><html><head><meta charset="UTF-8">' . $c->viaHead()
    . '<title>Report</title></head><body><main id="report">...</main>' . $c->viaFoot() . '</body></html>');

A template rendered outside a context, such as a 404 page from $app->notFound() through $app->getTwig(), can extend the same layout: there via_head() and via_foot() write only the import map and the Datastar script.

Content-Security-Policy

A middleware that sets the via.csp_nonce request attribute puts its nonce on every tag via_head and via_foot write, the import map included, and on the Dev Bar's tags. Datastar needs the nonce too. It reads it from a data-nonce attribute on the <html> element, and then runs data-* expressions and the scripts the server sends, from execScript(), dispatch() or a reload, as scripts with that nonce. Without data-nonce it compiles expressions with the Function constructor, which a policy blocks without 'unsafe-eval'.

The default shell writes data-nonce on <html> when the page request carries a nonce. A shell of your own writes it with {{ via_html_attrs }}, a Twig layout with {{ via_html_attrs() }}:

<!DOCTYPE html>
<html lang="en"{{ via_html_attrs() }}>
<head>
    <meta charset="UTF-8">
    {{ via_head() }}
</head>
<body>
    {% block content %}{% endblock %}
    {{ via_foot() }}
</body>
</html>

via_html_attrs writes nothing without a nonce, and nothing in an update render, so a morph of the document does not put back the attribute Datastar removed after reading it. For the same reason the tags of via_head and via_foot carry the nonce only on the page load, where the browser hides it from scripts. Dev mode warns once per shell or route whose page has a nonce and no data-nonce. The middleware sends the policy as a header on the response it gets back from $handler->handle(). This setup runs in Chromium with a counter, dispatch() and execScript() working and no CSP errors:

final class CspNonce implements MiddlewareInterface {
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        $nonce = base64_encode(random_bytes(16));
        $response = $handler->handle($request->withAttribute('via.csp_nonce', $nonce));

        return $response->withHeader('Content-Security-Policy', "default-src 'self'; script-src 'nonce-{$nonce}'; object-src 'none'; base-uri 'none'");
    }
}

$app->middleware(new CspNonce());
$app->page('/', fn (Context $c) => $c->view('home.html.twig'));

A <meta http-equiv="Content-Security-Policy"> before via_head works too, but it cannot set frame-ancestors: Config::withEmbeddable() sends that one as a header, next to the middleware's. A callable that returns a whole document writes the attribute itself, with the nonce the page handler reads:

$app->page('/report', function (Context $c): void {
    $nonce = htmlspecialchars((string) $c->getRequestAttribute('via.csp_nonce'));
    $c->view(fn (): string => "<!DOCTYPE html><html data-nonce=\"{$nonce}\"><head><meta charset=\"UTF-8\">"
        . $c->viaHead() . '</head><body><main id="report">...</main>' . $c->viaFoot() . '</body></html>');
});

Data in templates

A template gets the context's named signals as Signal objects and its named actions as Action objects, an action named add-todo as addTodo. It also gets contextId, currentRoute (the route pattern), basePath, via_html_attrs, via_head, via_foot and _via, which lists the names of both. What you pass in $data wins.

$count = $c->signal(0, 'count');
$inc   = $c->action(fn () => $count->setValue($count->int() + 1), 'inc');

// Signal 'count' → {{ count }}, a Signal: count.int, count.ref, count.id
// Action 'inc'   → {{ inc }}, an Action: inc.url
$c->view('counter.html.twig');

// Pass only what is neither a signal nor an action:
$c->view('todo.html.twig', ['todos' => $todos]);

Data read on every render

An array passed to view() is built once, when the page handler runs. When the view reads state from elsewhere, such as a database or countClients(), pass a callable, which runs on every render:

$c->view('presence.html.twig', fn (): array => ['count' => $app->countClients(Scope::routeScope('/'))]);

Reactive text

Use data-text to keep an element in step with a signal. Render the current value inside it, so the page shows it before the stream opens:

<span data-text="{{ count.class="hl-property">ref }}">{{ count.int }}</span>

In a PHP view, $signal->ref() gives the same reference:

$c->view(fn (): string => <<<HTML
    <span data-text="{$count->ref()}">{$count->int()}</span>
    HTML);

Two-way binding

Use data-bind for inputs that show a signal and update it:

<input {{ bind(name) }} type="text">
{# or by hand: <input data-bind="{{ name.class="hl-property">id }}" type="text"> #}

Datastar 1.0.5 updates a bound checkbox or radio on input, not change, so a script that sets one has to dispatch input. On a web component, bind a property: {{ bind(volume, 'value') }} renders data-bind__prop.value. See Web components.

Triggering actions

Use Datastar's event attributes to post to an action's URL:

<button data-on:click="@post('{{ inc.url }}')">+1</button>

{# Pass data in the query string, read with $c->input('option') #}
<button data-on:click="@post('{{ vote.url }}?option=tab')">Vote TAB</button>

Datastar 1.0.5 cancels a request still in flight when any element sends another one with the same method and URL. Two elements that post the same action at the same time need a query each, such as ?from=button. See Actions → Cancellation.

Template inheritance

Twig inheritance works inside views as everywhere:

{# section.html.twig #}
<nav><a href="/">Home</a></nav>
<div id="section">{% block content %}{% endblock %}</div>
{# page.html.twig #}
{% extends "section.html.twig" %}
{% block content %}
    <h1>My page</h1>
{% endblock %}

Blocks as update targets

Name a block, and view() sends only that block on updates while the page load renders the whole template:

$c->view('page.html.twig', fn (): array => ['items' => $repo->all()], block: 'demo');

The layout, nav and static content then go out once. Give the block a single root element with an id that is unique on the page, also against the shell (the default shell uses content): Datastar morphs the element with that id. See Views → Partial updates.

Debugging

The dump() function renders its arguments as a <pre> block:

{{ dump(some_variable) }}

Next steps