使用http://twig.sensiolabs.org/doc/advanced.html#creating-an-extension中的示例:在创建视图的主Slim
文件中:
$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,
));
结果:Call to undefined method Twig_Environment::appendData()
。
以各种方式尝试,例如:
$app->view(new \Slim\Views\Twig());
$app->view->parserExtensions = array(
new \Slim\Views\TwigExtension(),
);
$app->view->addFilter($filter);
但我只是不理解它应该如何运作。
答案 0 :(得分:9)
对于Slim 3来说,情况发生了变化。它可以在一行中完成:
^\s*<(title|price)[^>]*>(.*)<\/\1>
但如果没有上下文,这不是特别有用,所以这里有一个完整的示例,基于Slim框架网站提供的示例:http://www.slimframework.com/docs/features/templates.html
此代码演示了使用rot13
添加过滤器来编码文本$view->getEnvironment()->addFilter($filter);
html文件rot13.html包含:
<?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();
将浏览器指向 yourservername / rot13 / pineapple,您应该看到
{{text|rot13}}
答案 1 :(得分:4)
阿。只需要这两个班轮:
$twig = $app->view->getInstance();
$twig->addFilter($filter);