Yan's Blog

Yan's Blog

Write Your Own Filters and Functions in Twig

Write Your Own Filters and Functions in Twig

Subscribe to my newsletter and never miss my upcoming articles

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.

Create your own filters

For example, if we want to create filters bold and italic that make the characters on a web page become bold and italic, respectively like this:

{{ "Bold string"|bold }}

{{ "Italic string"|italic }}

Then we can create a new class that extends AbstractExtension and implement the function 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.

Create your own functions

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 the above code snippet, 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).

How to use

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"));

First, 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 to disable the autoescape option when initializing the Twig Environment. Then, we add the new created extension 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: Twig Extension Demo

#php#web-development
 
Share this