timworx/leaf-twig

Leaf PHP Framework adaptation of twig/twig package

Installs: 6

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/timworx/leaf-twig

v1.0.0 2025-10-21 09:05 UTC

This package is auto-updated.

Last update: 2025-12-21 09:36:11 UTC


README

Latest Stable Version Twig Version

The standalone version of Symfony's Twig templating engine for use in the Leaf framework.

This package is oriented towards the Leaf/Blade package.

Installation

Install using composer:

composer require timworx/leaf-twig

Usage

Create a Twig instance by passing it the folder(s) where your template files are located, and the Twig options like a cache folder. Render a template by calling the render method. More information about the Twig templating engine can be found on https://twig.symfony.com/.

use Leaf\Twig;

$twig = new Twig(['templates'], ['cache' => 'var/cache']);

You can also initialise it globally and configure the instace later.

$twig = new Twig;

// somewhere, maybe in a different file
$twig->configure(['templates'], ['cache' => 'var/cache']);

// alternative
$twig->config(['templates'], ['cache' => 'var/cache']);
echo $twig->render('index.html.twig', ['name' => 'John Doe']);
exit;

We can have this as our template index.html.twig

<!Doctype html>
<html>
    <head>
        <title>{{ name }}</title>
    </head>
    <body>
        <div class="container">{{ name }}</div>
    </body>
</html>

You can extend Twig using TwigFilters, TwigFunctions and Extensions:

// Function
$twig->addFunction('md5', function ($string) {
    return md5($string);
});

// Filter
$twig->addFilter('md5', function ($string) {
    return md5($string);
});

// Extension
$twig->addExtension(new \App\Extension\MyExtension()); // Your own created extension

Which allows you to use the following in your blade template:

MD5 hashed string with function: {{ md5(name) }}
MD5 hashed string with filter: {{ name|md5 }}

You can also set global variables:

$twig->addGlobal('myGlobal', 'The Value');

If you want to use additional Twig functions, you can access the Twig instance.

$twig->twig(); // The Twig environment instance

For more Twig directives check out the original documentation.