Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Text Template Laravel Package

phpunit/php-text-template

A tiny, dependency-free templating library used internally by PHPUnit. Render text with {placeholder} syntax using an associative array of values. Battle-tested and simple, it suits report generation, log formatting, and other human-readable output where a full template engine would be overkill.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer: composer require phpunit/php-text-template. This is a purely functional templating tool—no service provider, no config, no Laravel integration. Use the SebastianBergmann\Template\Template class directly to replace {placeholder} (escaped) or {!placeholder} (raw) markers. Start with a minimal example:

use SebastianBergmann\Template\Template;

$template = new Template('Welcome, {username}! Your balance is ${balance}.');
$output = $template->render([
    'username' => 'Alex',
    'balance'  => '1,250.00'
]);

echo $output; // "Welcome, Alex! Your balance is $1,250.00."

First use case: Generate CLI output, config stubs, or test fixtures—e.g., scaffolding .env.example files or static API response samples for docs.

Version note: Use 6.0.1+ if replacement values may contain placeholder-like text. It fixes render() re-processing {...} or {!...} sequences that were inserted as values for earlier placeholders.

Implementation Patterns

  • Template-as-source: Store templates in plain .tpl or .txt files and load via file_get_contents(). Ideal for pre-rendered artifacts (e.g., README snippets, migration stubs).
    $template = new Template(file_get_contents('stubs/migration.tpl'));
    file_put_contents('database/migrations/'.date('Y_m_d_His').'_create_users.php', $template->render(['table' => 'users']));
    
  • Composable templates: Render the inner template first, then pass its output as a normal value to the outer template. In 6.0.1+, inserted output is not rescanned for placeholders, so literal braces inside generated code or documentation remain intact.
    $inner = (new Template(file_get_contents('stubs/model.tpl')))->render(['model' => 'User']);
    $outer = new Template(file_get_contents('stubs/controller.tpl'));
    
    $controller = $outer->render(['model' => 'User', 'model_stub' => $inner]);
    
    If you need recursive substitution, do it explicitly with a second render() call rather than relying on the renderer to reprocess inserted values.
  • Test-driven generation: Use this to assert exact output from generators in tests (e.g., verify a config writer produces config/app.php matching a golden template). The 6.0.1 fix is helpful when fixture data contains template syntax intentionally.
  • CLI tooling: Wrap the engine in an artisan command to generate project boilerplate—e.g., php artisan make:template user-invite → populates resources/emails/user-invite.txt.
  • Caching strategy: Since render() compiles on every call, pre-instantiate templates for high-frequency use:
    $cachedTemplates = [];
    function getTemplate(string $name): Template {
        return $cachedTemplates[$name] ??= new Template(file_get_contents("templates/$name.tpl"));
    }
    

Gotchas and Tips

  • Zero logic, no helpers: No @if, @foreach, or @include—all branching/looping must be done before calling render(). Prepare arrays of data and flatten nested structures manually.
  • Escaping is subtle: {foo} escapes &, <, >, ", '—but only ASCII. {!foo} is raw HTML injection risk if used with user content. Override escaping via Template::escape() for custom behavior (e.g., JSON-safe output).
  • Placeholder precision matters: Whitespace like { foo } will not match ['foo' => 'bar']. Use exact keys with no spaces.
  • 6.0.1 behavior change: In 6.0.0 and earlier, a replacement value such as {name} or {!html} could be replaced again if another placeholder with that key was processed. 6.0.1 stops that. This is a bug fix, but it changes output for templates that accidentally relied on recursive replacement; use explicit multi-pass rendering if that behavior is intentional.
  • PHP version churn: Major version lines have changed PHP requirements. Pin your version range deliberately and verify compatibility with your target runtime before broad adoption.
  • Debugging blank output: Common causes: missing keys (key mismatches), template file not found (silent file_get_contents failure), or NULL values (silently rendered as empty string). Log array_keys() against the template string to validate.
  • Wrap, don’t extend: Since the class is final and has no DI hooks, create your own TextTemplateRenderer service to handle defaults, validation, and error logging—this keeps Laravel’s lifecycle clean.
  • Security: Never render untrusted input as template data without explicit validation—this engine assumes you sanitize the data array first. The 6.0.1 fix reduces accidental recursive replacement, but it does not make raw {!placeholder} output safe for user-supplied content.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console