Luminova Framework

PHP Luminova: Twig Template Engine Extension

Last updated: 2026-12-03 03:51:46

Render Twig templates with Luminova’s view context and template helpers.

Luminova’s Twig Template Extension exposes view options through Twig’s template context and registers helpers such as static, new, fn, and const. Templates can access data supplied by the controller through the self object.


Twig Support

  • 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

Select 'twig' in Template Configuration. See Template View Rendering for passing controller data to the template.


Template Context Object

Luminova exposes the Twig template context as self. Use it to read view options, call view methods, or access the attached application. For the built-in PHP engine’s scope rules, see PHP Template View Isolation.


Controller Example

namespace App\Controllers\Http;

use Luminova\Base\Http\AbstractController;

class MainController extends AbstractController
{
    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 in the controller before rendering:

namespace App\Controllers\Http;

use App\Utils\Example;
use App\Utils\StaticExample;
use Luminova\Base\Http\AbstractController;

class ExportExampleController extends AbstractController 
{
    protected function onCreate(): void
    {
        $this->tpl->export(Example::class, 'example'); 
        $this->tpl->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\Extensions → registerClasses().This allows you to 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\Extensions → 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\Extensions → registerFunctions().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\Extensions → getGlobals():

{{ 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() }}

Instantiate an object by alias

When a class is registered with registerClasses(), pass its alias to new(). The template can pass constructor arguments after the alias.

Example

{% set example = new('example', 'param1', 'param2') %}
{{ 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() is present in the application extension trait.