beecubu / php-foundation-templater
Simple templates compiler based on PHP Object Foundation Framework
v1.4.0
2024-03-02 01:44 UTC
Requires
- php: >=7.1.0
- ext-gettext: *
- beecubu/php-foundation-core: ^3.1
README
Simple template compiler based on PHP Object Foundation. It supports:
- HTML templates (
.html) - Native PHP templates (
.phtml) - Localization fallback (
.es.html,.es.phtml, etc.) - Simple directives like
@include,@foreach,@if,@date,@nl2br, and@subject
Requirements
- PHP 7.1+
ext-gettextbeecubu/php-foundation-core
Installation
composer require beecubu/php-foundation-templater
Quick Start
<?php
use Beecubu\Foundation\Templater\TemplateCompiler;
$compiler = TemplateCompiler::current();
$html = $compiler->compileStr(
'<h1>Hello {{ user.name }}</h1>',
'en',
['user' => ['name' => 'Ada']]
);
echo $html;
Template Loading
By default templates are searched in TEMPLATES_PATH:
define('TEMPLATES_PATH', __DIR__.'/Resources/Templates/');
You can add extra search paths (checked first):
TemplateCompiler::current()->appendTemplatesSearchPath(__DIR__.'/templates/');
When loading by name (compileTemplate*), it resolves in this order:
{name}.{locale}.phtml{name}.{locale}.html{name}.phtml{name}.html
Template names use dots as path separators:
emails.welcome -> emails/welcome.html
Directives
Variables
Hello {{ user.name }}
Includes
@include(header)
Conditionals
@if($user.isActive)
Active
@fi
Loops
@foreach($items)
<li>{{ $items.name }}</li>
@end
String Helpers
@nl2br($message)
Date Formatting
@date($order.createdAt, "en", "d/m/Y")
Subject
If you want to embed an email subject inside the template:
@subject(Welcome {{ user.name }})
<p>Body content here</p>
The @subject(...) tag is removed from the final HTML and the subject is returned separately.
API
// Compile raw template string
$body = TemplateCompiler::current()->compileStr($template, 'en', $data, $subject);
// Compile template by name from disk
$body = TemplateCompiler::current()->compileTemplateStr('emails.welcome', 'en', $data, $subject);
// Compile with callback
TemplateCompiler::current()->compile($template, 'en', $data, function (string $body, ?string $subject) {
// ...
});
Gettext (Optional)
If you use native templates (.phtml) and gettext, set the domain:
define('TEMPLATES_GETTEXT_DOMAIN', 'messages');
The compiler will switch the LANG environment variable to the requested locale during render and restore it afterwards.