Luminova Framework

PHP Luminova: Twig Templete Engine Extension

Last updated: 2025-12-05 06:43:39

Using the Twig template engine, to efficiently render templates and minimizing class initialization to save you the time and effort of manually registering classes and functions.

Luminova Twig template extension makes it easy to use the Twig template engine inside your Luminova applications. With Luminova, you get built-in template helpers like static, new, fn, and const that simplify template logic, reduce unnecessary class initialization, and improve overall performance.

This extension is designed to help developers build scalable and maintainable applications without spending time on repetitive boilerplate code. Using Twig in Luminova lets you focus on application logic while keeping templates fast and efficient.


Twig Support in Luminova

  • Supported Twig Version: 3.0
  • If a newer version causes issues, downgrade to ^3.0 for full compatibility.
  • Official Twig documentation: https://twig.symfony.com

Installation

Install Twig via Composer:

composer require twig/twig

Template Context Object

In Luminova Twig, the template context is exposed through a single self object.This works like Luminova’s default PHP template system, where your view options and view object are isolated and accessible through $self custom scope property.

Anything passed from your application object, view object or controller options, can be accessed using self.property or self.method().


Controller Example

namespace App\Controllers\Http;

use Luminova\Base\Controller;

class MainController extends Controller
{
    public function index(): int 
    {
        return $this->view('index', [
            'name' => 'Peter',
            'age' => 34
        ]);
    }
}

Accessing passed options in Twig templates

{{ self.name }}
{{ self.age }}

Default options always available

{{ self.title }}
{{ self.asset }}
{{ self.href }}

Accessing the view object

{{ self.getOptions() }}
{{ self.getOption('title') }}
{{ self.app.session.isOnline() }}

Exporting Properties and Classes

For the older “export to view” style, you can expose classes to all templates during application boot:

namespace App;

use App\Utils\Example;
use App\Utils\StaticExample;
use Luminova\Foundation\Core\Application as CoreApplication;

class Application extends CoreApplication 
{
    protected function onCreate(): void
    {
        $this->view->export(Example::class, 'example'); 
        $this->view->export(StaticExample::class);
    }
}

Accessing exported classes in Twig templates

{{ self.example.getValue() }}
{{ self.StaticExample.getValue() }}

Recommendation:

Prefer using {{ self.app.property }} or {{ self.app.method() }} over exporting classes manually.This keeps templates cleaner, easier to maintain, and fully compatible with future Luminova updates.


Calling Static Classes

In Luminova Twig, you can call static methods in two ways:

  1. Register the class inside App\Config\Templates\Twig\ExtensionsregisterClasses().This lets you call the class using a short alias in templates.

  2. Use the full namespace with the static helper.This does not require registration, avoids unnecessary class initialization, and is usually the more efficient choice.

The helper signature:

function static(string $class, string $member, mixed ...$arguments): mixed

Parameters

ParameterTypeDescription
$classstringFully qualified class name or registered alias.
$memberstringThe static property or method name to call.
$argumentsmixedOptional method arguments.

Note:static() is not a real PHP function.It only works inside Twig templates.


Examples

1. Calling a registered class (from registerClasses)

{{ static('Example', 'getName') }}
{{ static('Example').getName() }}

2. Set a value and get it immediately

{{ static('Example', 'setName', 'Peter').getName() }}

3. Call a static method using the full namespace

{{ static('App\\Utils\\Example', 'getName') }}
{{ static('App\\Utils\\Example').getName() }}

4. Set a value and retrieve it in one line

{{ static('\\App\\Utils\\Example', 'setName', 'names').getName() }}

Instantiate a Class Object

In Luminova Twig, you can create a new class instance directly in templates and access its methods or properties.

There are two main approaches:

  1. Register the class inside App\Config\Templates\Twig\ExtensionsregisterFunctions() or registerClasses().This allows you to use a short alias in templates.

  2. Use the full namespace with the new helper.This avoids registration and resolves the class directly if it exists. It is usually more efficient.

The helper signature:

function new(string $class, mixed ...$arguments): object

Parameters

ParameterTypeDescription
$classstringFully qualified class name or registered alias.
$argumentsmixedConstructor arguments to pass to the class.

Note:new() is not a PHP function.It only works inside Twig templates.


Instance Examples

1. Initialize an object using a registered alias

{{ new('Example', 'Peter').getName() }}

Assign the object to a variable

{% set example = new('Example', 'Peter') %}
{{ example.getName() }}

2. Initialize an object using the full namespace

{{  new('\\App\\Utils\\Example').getName() }}

Assign object to a variable

{% set example = new('\\App\\Utils\\Example') %}
{{ example.getName() }}

Access object properties

{{ example.name }}
{{ example.getName() }}

Call Functions

In Luminova Twig, you can call functions inside templates in two ways:

  1. Register the function inside App\Config\Templates\Twig\ExtensionsregisterFunctions().This allows you to expose functions.

  2. Call functions directly using the fn helper.Luminova provides a built-in helper class extended from \Twig\TwigFunction to keep function calls consistent.

Note:

Even without using fn, Luminova will resolve the correct function, including namespaced Luminova helpers and core PHP functions.Use fn explicitly when you want to call functions directly in templates.

Aliases:func and function behave exactly the same as fn.


The helper signature:

function fn(string $function, mixed ...$arguments): mixed

Parameters

ParameterTypeDescription
$functionstringThe function name (e.g., Luminova\\Funcs\\escape, strlen).
$argumentsmixedOptional function arguments.

Note:fn() is not a PHP function.It only works inside Twig templates.


Functions Examples

1. Call a registered or global function

{{ myFunction() }}
{{ root('path/to/file', 'filename.json') }}

2. Call a function explicitly using fn

{{ fn('myFunction') }}

3. Call a namespaced Luminova helper

{{ fn('Luminova\\Funcs\\root', 'path/to/file', 'filename.json') }}

4. Call a Luminova helper without namespace

{{ fn('root', 'path/to/file', 'filename.json') }}

Get Constants

In Luminova Twig, you can access constants directly if they are exposed as globals in App\Config\Templates\Twig\ExtensionsgetGlobals():

{{ APP_NAME }}

For better flexibility, Luminova provides a const helper. This helper allows you to access any globally defined constant without manually exposing each one. Using const helps keep your templates maintainable and future-proof.


The helper signature:

function const(string $name): mixed

Parameters

ParameterTypeDescription
$namestringThe name of the constant to retrieve (e.g., APP_NAME, STATUS_SUCCESS).

Note:const() is not a PHP function.It only works inside Twig templates.


Constants Example

Print your application name using the const helper:

{{ const('APP_NAME') }}

Twig Extensions Registration Pattern

Namespace: App\Config\Templates\Twig\Extensions

Luminova Twig provides several helper methods in extensions configuration class to register classes, objects, functions, and global constants. These registration methods allow templates to access PHP classes and functions efficiently, keeping templates clean and maintainable.


registerClasses

Use registerClasses() to expose static classes or classes that will primarily be accessed via static methods.

Pattern:

public function registerClasses(): array
{
    return [
        'example' => \App\Utils\Example::class,
    ];
}

Twig Usage:

{{ static('example', 'getValue') }}
{{ new('example', 'getValue') }}

registerObjects

Use registerObjects() to expose objects that will be instantiated in templates.

Pattern:

public function registerObjects(): array
{
    return [
        'example' => new \App\Utils\Example('param1', 'param2'),
    ];
}

Twig Usage:

{{ new('example').getName() }}

{% set example = new('example') %}
{{ example.getName() }}

registerFunctions

Use registerFunctions() to expose PHP functions, helpers, or closures to templates.

Pattern:

use Twig\TwigFunction;

public function registerFunctions(): array
{
    return [
        new TwigFunction('hello', static fn($name) => "Hello $name"),
        new TwigFunction('flash', static fn(string $key) => \App\Utils\Messages\flash($key)),
    ];
}

Twig Usage:

{{ hello('Peter') }}
{{ flash('success') }}

getGlobals

Use getGlobals() to expose constants or global variables to templates.

Pattern:

public function getGlobals(): array
{
    return [
        'APP_NAME' => APP_NAME,
        'APP_VERSION' => APP_VERSION,
        'PRODUCTION' => PRODUCTION,
    ];
}

Twig Usage:

{{ APP_NAME }}
{{ APP_VERSION }}
{{ PRODUCTION }}

getFilters

Use getFilters() to register Twig filters.

Pattern:

use \Twig\TwigFilter;

public function getFilters(): array
{
    return [
        new TwigFilter('upper', 'strtoupper'),
        new TwigFilter('escape_html', fn($value) => htmlspecialchars($value, ENT_QUOTES, 'UTF-8')),
    ];
}

Twig Usage:

{{ 'hello'|upper }}
{{ '<b>Test</b>'|escape_html }}

Optional:

Filters, Tests, and Operators

  • Tests: Use getTests() to register Twig tests.
  • Operators: Use getOperators() to register custom operators.