Search by

ziraphp / templating

Subu-07

Twig templating for ZiraPHP: template rendering, HTML responses, route URLs and versioned assets.

v0.1.0 2026-12-04 08:38 UTC

This package is auto-updated.

Last update: 2026-12-04 08:43:00 UTC


README

Twig templates for ZiraPHP: HTML responses from your handlers, route and asset URLs in templates, and commands to lint and precompile templates.

  • View turns a template into a PSR-7 HTML response, or renders a single block for HTMX/AJAX fragments.
  • path(), url() and asset() Twig functions, with webpack and Vite manifest support for cache-busted asset URLs.
  • Output is escaped by default; debug mode adds dump(), strict variables and template reloading.
  • view:lint, view:cache and view:clear commands.
composer require ziraphp/templating

Requires PHP 8.2+ and ziraphp/framework ^0.1. Add ziraphp/console for the view:* commands and ziraphp/service-provider to configure it from config/templating.php.

Setup

In a ZiraPHP application

With ziraphp/service-provider, TemplatingServiceProvider is discovered automatically and reads config/templating.php. Every key is optional:

// config/templating.php
return [
    'paths' => ['templates', 'admin' => 'templates/admin'], // "admin" templates are "@admin/..."
    'cache' => 'var/cache/twig',      // false compiles on every request
    'debug' => null,                  // defaults to the application's debug mode
    'strict_variables' => null,       // defaults to debug
    'auto_reload' => null,            // defaults to debug
    'autoescape' => 'html',           // or 'name' (by file extension), or false
    'charset' => 'UTF-8',
    'globals' => ['app_name' => 'Acme'],
    'base_url' => 'https://example.com', // needed by url()
    'assets' => [
        'base_url' => '/build',
        'version' => null,            // appended as ?v=... when there is no manifest entry
        'manifest' => 'public/build/manifest.json',
    ],
    'extensions' => [App\Twig\MarkdownExtension::class], // built from the container
];

Relative paths are resolved against the application's base path.

Without ziraphp/service-provider, pass the configuration to the provider:

$app->register(new TemplatingServiceProvider(['paths' => ['templates']]));

The provider binds Twig's Environment, TemplateRendererInterface (as TwigRenderer), View, Assets and TwigFactory, and adds the commands when ziraphp/console is installed.

Standalone

use ZiraPHP\Templating\TwigFactory;
use ZiraPHP\Templating\TwigRenderer;

$twig = (new TwigFactory(__DIR__))->create(['paths' => ['templates'], 'cache' => false], $router);
$renderer = new TwigRenderer($twig);

echo $renderer->render('home.html.twig', ['name' => 'Ada']);

Rendering responses

Inject View into handlers:

use Psr\Http\Message\ResponseInterface;
use ZiraPHP\Templating\View;

final class PostController
{
    public function __construct(private readonly View $view)
    {
    }

    public function show(int $id): ResponseInterface
    {
        return $this->view->render('posts/show.html.twig', ['post' => $this->posts->find($id)]);
    }
}
Method Returns
render($name, $context, $status = 200, $headers = []) An HTML response
renderBlock($name, $block, $context, $status, $headers) One block as an HTML response
fetch($name, $context) The rendered string
exists($name) Whether the template can be loaded

renderBlock() is handy for partial updates: render the items block of the full page instead of keeping a separate fragment template.

A missing template throws TemplateNotFoundException; other Twig errors throw TemplatingException. Both keep Twig's error, with the template name and line, as the previous exception.

Twig functions

<a href="{{ path('posts.show', {id: post.id}) }}">{{ post.title }}</a>
<link rel="canonical" href="{{ url('posts.show', {id: post.id}) }}">
<script type="module" src="{{ asset('resources/app.ts') }}"></script>
  • path(name, params) generates the path of a named route with the router.
  • url(name, params) prefixes that path with base_url.
  • asset(path) builds a public URL. With a manifest, the built file name is used ("app.js": "app.3f9c2a.js" from webpack, or {"file": ...} entries from Vite); otherwise assets.version is appended as ?v=.... Absolute URLs pass through unchanged.

Add your own functions and filters with Twig extensions in extensions.

Commands

With ziraphp/console:

Command Does
view:lint [templates...] Checks every template (or the named ones) for syntax errors. Fails if any have errors.
view:cache Compiles every template into the cache, e.g. during deployment.
view:clear Deletes the compiled templates.

Development

composer install
composer check   # tests, PHPStan, Psalm and coding standards

License

MIT. See LICENSE.