如何在 Slim 中向我的 Twig 模板添加自定义过滤器? [英] How can I add a custom filter to my Twig templates inside of Slim?
问题描述
使用 http://twig.sensiolabs.org/中的示例doc/advanced.html#creating-an-extension:在我创建视图的主要 Slim
文件中:
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,
));
结果:调用未定义的方法 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.
推荐答案
对于 Slim 3,事情发生了变化.它可以在一行中完成:
For Slim 3, things have changed. It can be done in one line:
$view->getEnvironment()->addFilter($filter);
但是如果没有上下文,这不是特别有用,所以这里有一个完整的示例,基于 Slim Framework 网站上提供的示例:http://www.slimframework.com/docs/features/templates.html
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
此代码演示了添加过滤器以使用 rot13 对文本进行编码
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();
html 文件 rot13.html 包含:
And the html file rot13.html contains:
{{text|rot13}}
将浏览器指向 yourservername/rot13/pineapple,您应该会看到
Point your browser at yourservername/rot13/pineapple and you should see
cvarnccyr
这篇关于如何在 Slim 中向我的 Twig 模板添加自定义过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!