beecubu/php-foundation-templater

Simple templates compiler based on PHP Object Foundation Framework

Installs: 91

Dependents: 0

Suggesters: 0

Security: 0

pkg:composer/beecubu/php-foundation-templater

v1.4.0 2024-03-02 01:44 UTC

This package is auto-updated.

Last update: 2026-02-04 18:21:29 UTC


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-gettext
  • beecubu/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:

  1. {name}.{locale}.phtml
  2. {name}.{locale}.html
  3. {name}.phtml
  4. {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.