我想在 Slim3 中制作简单的模板渲染,但出现错误:
这是我的代码:命名空间控制器;
class Hello
{
function __construct() {
// Instantiate the app
$settings = require __DIR__ . '/../../src/settings.php';
$this->app = new 'Slim'App($settings);
}
public function index(){
return $this->app->render('web/pages/hello.phtml'); //LINE20
}
}
这是我得到的错误:
Message: Method render is not a valid method
App
对象本身不处理任何渲染,您需要一个模板插件,可能是基于模板.phtml
扩展的模板插件。使用作曲家安装:
composer require slim/php-view
然后,您的控制器方法将执行以下操作:
$view = new 'Slim'Views'PhpRenderer('./web/pages');
return $view->render($response, '/hello.phtml');
你最终希望将渲染器放在依赖项注入容器中,而不是在控制器方法中创建新实例,但这应该可以让你入门。
我通过将渲染器粘贴在容器中来处理这个问题。将其粘贴到您的主index.php
文件中。
$container = new 'Slim'Container($configuration);
$app = new 'Slim'App($container);
$container['renderer'] = new 'Slim'Views'PhpRenderer("./web/pages");
然后在Hello
类的文件中。
class Hello
{
protected $container;
public function __construct('Slim'Container $container) {
$this->container = $container;
}
public function __invoke($request, $response, $args) {
return $this->container->renderer->render($response, '/hello.php', $args);
}
}
若要清理此代码,请创建一个基本处理程序,该处理程序已为您封装了此呈现逻辑。