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

ⅰ亾dé卋堺 提交于 2020-08-22 06:09:05

问题


Using the example from http://twig.sensiolabs.org/doc/advanced.html#creating-an-extension: within my main Slim file 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 in: Call to undefined method Twig_Environment::appendData().

Tried in various ways such as this:

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

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

but I'm just not understanding how it's supposed to work.


回答1:


For Slim 3, things have changed. It can be done in one line:

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

But that isn't particularly useful without context, so here is a full sample, based on the example provided at 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 yourservername/rot13/pineapple and you should see

cvarnccyr



回答2:


Ah. Just needed this two liner:

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


来源:https://stackoverflow.com/questions/27714854/how-can-i-add-a-custom-filter-to-my-twig-templates-inside-of-slim

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!