Nomisoft
Menu

Twig keyword highlighting extension

20th May 2015

I recently had the need to highlight certain keywords within some output from a twig template in a Silex project. Below is a simplified version of the Twig extension I wrote to perform this functionality. The version I actually used in the project included pulling a list of keywords from a database but other than that the rest of the class was as below. This should work fine in Silex, Symfony or any other framework making use of Twig.

The Code


namespace Nomisoft\Twig;

class HighlightTwigExtension extends \Twig_Extension {

    public function getFilters() {
        return array(
            new \Twig_SimpleFilter('highlight', array($this, 'highlightFilter'), array('is_safe' => array('html'))),
        );
    }

    public function highlightFilter($text)
    {
        $keyword = '{abc}';
        return preg_replace($keyword,'<span class="highlighted">$0</span>',htmlentities($text));
    }

    public function getName() {
        return 'highlight_twig_extension';
    }
}

Usage


{{ title|highlight }}

Now when I output the title variable it will wrap any occurrence of 'abc' in a span tag with the class 'highlighted' which I can style with CSS. For example if title contains 'abcdef' it will output <span class="highlighted">abc</span>def

The steps to get the Twig extension up and running in Silex or Symfony can be seen below

Silex


$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
    $twig->addExtension(new \Nomisoft\Twig\HighlightTwigExtension());
    return $twig;
}));

Symfony


# app/config/services.yml
services:
    app.twig_extension:
        class: Nomisoft\Twig\HighlightTwigExtension
        public: false
        tags:
            - { name: twig.extension }