Wednesday, 18 November 2020

Write your own filters and functions in Twig

PHP  Twig 

Twig provides a flexible way to make extensions. By implementing the Twig AbstractExtension class, you can create your own custom filters and functions that can be used in templates.

Suppose we want to create filters bold and italic that make the characters on a web page become bold and italic respectively:

{{ "Bold string"|bold }}

{{ "Italic string"|italic }}

Create a new class that extends AbstractExtension and implement the functions getFilters():

//MyExtension.php

use \Twig\Extension\AbstractExtension;
use \Twig\TwigFilter;

class MyExtension extends AbstractExtension {
    public function getFilters() {
        return [
            new TwigFilter('bold', [$this, 'makeBold']),
            new TwigFilter('italic', [$this, 'makeItalic']),
        ];
    }

    public function makeBold($str) {
        return '<b>'.$str.'</b>';
    }

    public function makeItalic($str) {
        return '<i>'.$str.'</i>';
    }    

}

In the above code snippet, we return two TwigFilter objects for filters bold and italic in the function getFilters(). Functions makeBold($str) and makeItalic($str) implement the logic for making characters to be bold and italic in html code.

If you want to create a function, implement the function getFunctions() like this:

//MyExtension.php

use \Twig\Extension\AbstractExtension;
use \Twig\TwigFilter;
use \Twig\TwigFunction;

class MyExtension extends AbstractExtension {
    public function getFilters() {
        return [
            new TwigFilter('bold', [$this, 'makeBold']),
            new TwigFilter('italic', [$this, 'makeItalic']),
        ];
    }

    public function getFunctions() {
        return [
            new TwigFunction('getArea', [$this, 'getArea']),
        ];
    }

    public function makeBold($str) {
        return '<b>'.$str.'</b>';
    }

    public function makeItalic($str) {
        return '<i>'.$str.'</i>';
    }    

    public function getArea($len) {
        return $len * $len;
    }
}

In line 11, we return a new TwigFunction object for calculating the area of a square in the function getFunctions(). The detail logic is defined in the function getArea($len).

To test the new created Twig extensions, we can do like this:

require_once './vendor/autoload.php';
require_once 'MyExtension.php';

$loader = new \Twig\Loader\FilesystemLoader('./themes');

$twig = new \Twig\Environment($loader, ['autoescape' => false]);

$twig->addExtension(new MyExtension());

echo $twig->render('test-extension.twig', array("len" => "9"));

In line 1, Composer's PHP file autoload.php is included to map the Twig's namespaces to real folders. In order to insert the HTML code into the template when using our new created filters, we need disable the autoescape option when initializing the Twig Environment in line 6. Then, in line 8, we add the new created extention MyExtension. Finally, we render the template test-extension.twig by passing the the length of one side of a square, len.

In the template test-extension.twig, we can call bold, italic and getArea() as below:

<h1>{{ "Twig Extension Demo"|italic }}</h1>
<p>
If the length of one side of a square is {{ len|bold }} meter, 
the area of the square is {{ getArea(len)|bold }} square meters.
</p>

After rendering, the web page will look like this:

Twig Extension Demo


Search