Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom filters for Twig in Silex

I need to add custom filter for Twig in Silex framework. For example, I want apply this function to some variable:

public function addExclamation($text) {
    return $text.'!!!';
}

And in twig-template do something like this:

{{ text|exclam }}

After reading http://twig.sensiolabs.org/doc/advanced.html I create "Project_Twig_Extension.php":

class Project_Twig_Extension extends Twig_Extension
{
    public function getName()
    {
        return 'project';
    }

    public function getFilters()
    {
        return array(
            new Twig_SimpleFilter('exclam', 'addExclamation'),
        );
    }

    public function addExclamation($text) {
        return $text.'!!!';
    }
}

But I can't undersand where I need to put this file and how I can register this filter in "index.php" of Silex.

Can you give me step-by-step guide? Method, described at Twig addFilter using Silex? don't work.

like image 411
inetbug Avatar asked Nov 30 '25 00:11

inetbug


1 Answers

You can add custom filters like this:

$app['twig'] = $app->share($app->extend('twig', function(\Twig_Environment $twig) {
    $twig->addFilter(new Twig_SimpleFilter('exclaim', function ($value) {
        return $value.'!!!';
    }));

    return $twig;
}));

Reference: http://silex.sensiolabs.org/doc/providers/twig.html#customization

like image 171
Garrett Avatar answered Dec 03 '25 11:12

Garrett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!