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

落花浮王杯 提交于 2019-12-03 17:03:19
Phippsy

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

Ah. Just needed this two liner:

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