Skip to content

PHP library that permit to render templates and permit to define which renderer to use

License

Notifications You must be signed in to change notification settings

comhon-project/template-renderer

Repository files navigation

PHP Template Renderer

  • Your library needs to render templates (example: email template) but you don't want to implement it ?
  • You want your template renderer to be customizable by developers that use your library ?

This library is made for that! it permit to render templates and permit to define which renderer to use. This library is generally intended for Laravel projects but you can use it even if you are not implementing a Laravel project.

There is only one renderer available by default (twig), but you can add your own by defining your own driver.

Installation

You can install the package via composer:

composer require comhon-project/template-renderer

For laravel project, you can publish the config file with:

php artisan vendor:publish --tag="template-renderer-config"

Usage

Laravel project

$rendered = Template::render(
    'Hello {{ user.name }} !!!',
    ['user' => ['name' => 'john doe']]
);

echo $rendered;
// output: Hello john doe !!!

Non Laravel project

use Comhon\TemplateRenderer\TemplateManager;

// the instantiation mechanism should be implemented in a specific place
// and called only one time (TemplateManager should be used as singleton)
$templateManager = new TemplateManager($app);

$rendered = $templateManager->render(
    'Hello {{ user.name }} !!!',
    ['user' => ['name' => 'john doe']]
);

echo $rendered;
// output: Hello john doe !!!

Adding custom renderer driver

First, you will have to define a class that implements Comhon\TemplateRenderer\Renderers\RendererInterface

<?php
use Comhon\TemplateRenderer\Renderers\RendererInterface;

class MyTemplateRenderer implements RendererInterface
{
    public function setDefaultLocale(string $locale) {}
    public function setDefaultTimezone(string $timezone) {}
    public function validate(string $template) {}
    public function render(
        string $template,
        array $replacements,
        string $defaultLocale = null,
        string $defaultTimezone = null,
        string $preferredTimezone = null
    ): string {}
}

Then, you will have to register your driver by calling the Template facade's extend method:

    Template::extend('my-renderer', function ($app) {
        return new MyTemplateRenderer($app);
    });

In laravel project, you may call this function in the boot method of your AppServiceProvider

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Credits

License

The MIT License (MIT). Please see License File for more information.

About

PHP library that permit to render templates and permit to define which renderer to use

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages