Unified Template Rendering Made Simple For PHP
A modern, flexible PHP template rendering library that provides a unified interface for multiple template engines and output formats.
Features
- 🔄 Unified Interface: One consistent API for all template engines.
- 🚀 Multiple Engine Support: Works with Twig, PHP, Markdown and more.
- đź“„ Multiple Output Formats: Generate HTML, PDF from any template.
- 🔌 Extensible Architecture: Easy to add new engines and formats.
- 🎨 Powerful Formatting System: Format data consistently across all templates.
- 🛡️ Secure by Design: Safe template rendering and file handling.
- 🪶 Lightweight Core: Only load what you need.
- ⚡ Framework Agnostic: Use with any PHP framework.
Why Derafu\Renderer?
Traditional template systems often lock you into a single engine or require different handling for each format. Derafu\Renderer solves this by providing:
- A single, clean API for all template engines.
- Seamless switching between output formats.
- Consistent data formatting across all templates.
- Framework-agnostic design.
- Easy integration with existing systems.
Installation
Install via Composer:
composer require derafu/renderer
Basic Usage
Import the shared service configuration as shown below, contribute your template
directories and inject RendererInterface into the service that renders them:
namespace App\Service;
use Derafu\Renderer\Contract\RendererInterface;
final class GreetingRenderer
{
public function __construct(private readonly RendererInterface $renderer)
{
}
public function render(string $name, int $quantity): string
{
return $this->renderer->render('greeting.html.twig', [
'name' => $name,
'quantity' => $quantity,
]);
}
}
For PDF output, import renderer-pdf-services.yaml, install its optional backend
and select the engine in the rendering options:
$pdf = $renderer->render('greeting.html.twig', ['name' => 'John', 'quantity' => 3], ['engine' => 'pdf']);
Dependency Injection and Domain Contributions
Import renderer-services.yaml for a working Twig renderer. It imports the actual
Twig service configuration and registers RendererInterface, a shared
FormatterInterface, the Twig engine and a provider for the formatter’s Twig
extension. Service IDs use interfaces; engines and providers in tagged collections
have individual implementation IDs.
imports:
- { resource: '../vendor/derafu/renderer/resources/config/renderer-services.yaml' }
Inject Derafu\Renderer\Contract\RendererInterface instead of reconstructing
it in each library or application. The scalar default-engine setting is
derafu.renderer.default_engine, whose default is twig.
Template Directories
Each domain contributes its own TemplatePathProviderInterface through the
derafu_twig.template_path_provider tag. The shared path provider is used for
Twig, PHP and Markdown template lookup. See
Template Path Providers.
Higher tag priorities are searched first. Libraries and applications can therefore compose search orders such as site, Pro, Core and package defaults without copying all directories into a new renderer definition. Changing a provider’s priority can change which template is selected when names collide; choose priorities deliberately.
Named Formatting Handlers
Implement Derafu\Renderer\Contract\FormatterHandlerProviderInterface to
contribute a map of handler names to the same handler values accepted by
DataFormatter: handler objects, masks or value maps. For example:
namespace App\Billing;
use Derafu\Renderer\Contract\FormatterHandlerProviderInterface;
use Derafu\Renderer\Contract\HandlerFormatterInterface;
final class BillingFormatterHandlerProvider implements FormatterHandlerProviderInterface
{
public function __construct(private readonly HandlerFormatterInterface $handler)
{
}
/**
* {@inheritDoc}
*/
public function getHandlers(): array
{
return ['billing_document' => $this->handler];
}
}
services:
Derafu\Renderer\Contract\HandlerFormatterInterface $billing:
class: App\Billing\BillingFormatter
App\Billing\BillingFormatterHandlerProvider:
arguments:
$handler: '@Derafu\Renderer\Contract\HandlerFormatterInterface $billing'
tags:
- { name: derafu_renderer.formatter_handler_provider, priority: 100 }
The qualified handler ID distinguishes a domain’s handler from other implementations
of the same contract. Providers are consumed in descending tag-priority order; the
first contribution for each name wins, while other names accumulate. Explicit
constructor handlers take precedence over providers, and registerHandler() can
still replace a handler afterward.
Core can contribute billing_document; Pro can replace that name at a higher
priority and add common and payslip; an application can add jt without copying
any previous map. FormatterExtensionProvider, tagged
derafu_twig.extension_provider, gives Twig the very same FormatterInterface
used by consumers formatting directly. Changes to that formatter are visible in
subsequent template rendering. Expressions such as
{{ value|format_as('billing_document.amount') }}keep their existing syntax.
Optional Engines
Additional engines have opt-in production configurations. Each imports the base
renderer composition; the Markdown configuration also imports Markdown’s own
services. Install derafu/markdown when enabling that engine.
| Configuration | Engine | Parameters |
|---|---|---|
renderer-php-services.yaml |
PHP | derafu.renderer.php.wrapper_template, .content_var_name, .vars_prefix |
renderer-markdown-services.yaml |
Markdown | derafu.renderer.markdown.wrapper_template, .content_var_name |
renderer-pdf-services.yaml |
derafu.renderer.pdf.options |
imports:
- { resource: '../vendor/derafu/renderer/resources/config/renderer-pdf-services.yaml' }
This adds PDF without replacing Twig, formatter contributions or template roots.
Install the optional dependencies for the engines you enable. Markdown uses shared
roots first and retains the Markdown service’s own lookup as a fallback. PDF uses
the same Twig environment and formatter; runtime config.pdf options keep their
existing meaning.
Custom engines implement EngineInterface and join the
derafu_renderer.engine tagged collection. The iterable registration uses
getName(); the first engine of each name wins according to tag priority. Direct
named-array construction still preserves explicit aliases, and addEngine()
retains its replacement behavior.
Existing or Independent Twig Environments
Override TwigServiceInterface with an existing environment as described in
Twig Service. Renderer uses
that environment without adding extensions or changing its loader. If its templates
need format_as, the environment’s owner must register the formatter extension
using the same formatter; it is not attached implicitly.
Independent renderers can use qualified interface bindings, a separate Twig creator/service and a separate engine tag. They need not replace either the application’s global renderer or Symfony’s native Twig environment.
Template Engines
Twig Templates
{# greeting.html.twig #}
<h1>Hello {{ name }}!</h1>
<p>Quantity: {{ quantity|format_as('%d') }}</p>
The format_as filter is provided by the shared formatter extension. A sprintf
mask such as %d needs no named handler. Formats such as billing_document.amount
require a handler contributed by the application or library.
PHP Templates
// greeting.php
<h1>Hello <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>!</h1>
<p>Quantity: <?= $format_as($quantity, '%d') ?></p>
Enable the PHP engine with renderer-php-services.yaml. Input data is available
as PHP variables. The generated HTML is placed in the Twig wrapper configured by
derafu.renderer.php.wrapper_template; provide that wrapper in your template paths.
The wrapperTemplate field in the render data selects a different Twig wrapper.
It must be a string; a missing field or null uses the engine’s configured
wrapper. Other types raise a translatable ConfigurationException. The PHP engine
always uses a wrapper.
Markdown Templates
# Hello!
This page is written in **Markdown**.
Enable the Markdown engine with renderer-markdown-services.yaml. It delegates
content rendering to the shared Markdown service and places the resulting HTML in
a Twig wrapper. See The Wrapper of the Markdown
for selecting or disabling that wrapper.
Configuration
Configure scalar settings through parameters. Template directories, named formatting handlers, Twig extensions and components are contributed by providers and their corresponding tags, rather than by redefining the renderer.
| Parameter | Purpose | Default |
|---|---|---|
derafu.renderer.default_engine |
Engine used when no engine is selected explicitly or inferred from the template extension. | twig |
derafu.renderer.php.wrapper_template |
Twig wrapper for PHP output. | html |
derafu.renderer.php.content_var_name |
Wrapper variable containing PHP output. | content |
derafu.renderer.php.vars_prefix |
Prefix of variables created by a PHP template that are passed back to the wrapper context. | __view_ |
derafu.renderer.markdown.wrapper_template |
Twig wrapper for Markdown output; null disables it. |
html |
derafu.renderer.markdown.content_var_name |
Wrapper variable containing Markdown output. | content |
derafu.renderer.pdf.options |
PDF options, including local_assets_path for local files referenced by root-relative asset URLs. |
{} |
PHP, Markdown and PDF parameters belong to their respective optional configuration
files. Twig’s settings remain under derafu.twig.*; see
Twig Service.
For example, enable PDF with a local asset root:
imports:
- { resource: '../vendor/derafu/renderer/resources/config/renderer-pdf-services.yaml' }
parameters:
derafu.renderer.pdf.options:
local_assets_path: '%kernel.project_dir%/public'
This example uses Symfony’s kernel.project_dir parameter. Other containers must
provide the corresponding application path.
Components
For Derafu Twig Components, import their optional integration alongside the renderer:
imports:
- { resource: '../vendor/derafu/renderer/resources/config/renderer-services.yaml' }
- { resource: '../vendor/derafu/twig-components/resources/config/twig-components-twig-services.yaml' }
This contributes the component classes and their template paths to the shared Derafu Twig environment. It reuses the renderer’s existing service graph. The components also need their translations and frontend assets; see Derafu integration.
For an existing Symfony Twig environment, use the Twig Components Bundle. Its native Symfony UX registration is shared by every consumer of that environment.
Formatting in the Templates
The templates of the Twig and PHP engines have two helpers of the formatting system:
format_as(value, format)formats the value with the handler of the format (the name of a handler, orhandler.format).to_string(value)converts it to text: a scalar andnullas text (nullis empty), an object that can be a string as its text, and any other value, an array for example, as JSON.
<p>{{ amount|format_as('%.2f') }}</p>
<pre>{{ {'a': 1, 'b': [2, 3]}|to_string }}</pre>
In a PHP template they are the variables $format_as and $to_string, which are closures.
The Wrapper of the Markdown
The Markdown engine puts the HTML of the Markdown inside a Twig template, html by default, in the variable content. A different wrapper goes in the data or in the options with wrapperTemplate, and false (or null, in the engine) means no wrapper: the result is the HTML of the Markdown.
$renderer->render('page.md', ['wrapperTemplate' => 'article']);
$renderer->render('page.md', [], ['wrapperTemplate' => false]);