How do I add a custom filter to my Twig templates inside Slim?

Using an example from http://twig.sensiolabs.org/doc/advanced.html#creating-an-extension : in my main file Slim

that creates the view:

$filter = new Twig_SimpleFilter( 'stripslashes', function ( $string ) { 
    return stripslashes( $string );
});

$loader = new \Twig_Loader_String();
$twig = new Twig_Environment($loader);
$twig->addFilter($filter);

$app->view($twig);

$app->view()->setData( array(
    'nav' => $nav,
    'sidenav' => $sidenav,
));

      

Results: Call to undefined method Twig_Environment::appendData()

.

Tried it in different ways like this:

$app->view(new \Slim\Views\Twig());
$app->view->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
);

$app->view->addFilter($filter);

      

but I just don't understand how this is supposed to work.

+5


source to share


2 answers


For Slim 3, everything has changed. This can be done in one line:

$view->getEnvironment()->addFilter($filter);

      

But this is not particularly useful without context, so here is a complete sample based on the example provided on the Slim Framework website: http://www.slimframework.com/docs/features/templates.html

This code demonstrates adding a filter to encode text with rot13

<?php
// Create app
$app = new \Slim\App();

// Get container
$container = $app->getContainer();

// Register component on container
$container['view'] = function ($container) {
   $view = new \Slim\Views\Twig('path/to/templates', [
       'cache' => 'path/to/cache'
    ]);
    $view->addExtension(new \Slim\Views\TwigExtension(
        $container['router'],
        $container['request']->getUri()
    ));

    $filter = new Twig_SimpleFilter('rot13', function ($string) {
        return str_rot13($string);
    });

    $view->getEnvironment()->addFilter($filter);

    return $view;
};

// Render Twig template in route
$app->get('/rot13/{text}', function ($request, $response, $args) {
    return $this->view->render($response, 'rot13.html', [
        'name' => $args['text']
    ]);
})->setName('rot13');

// Run app
$app->run();

      



And the html file rot13.html contains:

{{text|rot13}}

      

Point your browser at your server name / rot 13 / an pineapple and you should see

cvarnccyr

      

+9


source


Oh. We just needed two liners:



$twig = $app->view->getInstance();
$twig->addFilter($filter);

      

+4


source







All Articles