Slim 3渲染方法无效

时间:2016-01-15 09:08:16

标签: php slim

我想在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

2 个答案:

答案 0 :(得分:1)

App对象无法自行处理任何呈现,您需要一个模板加载项,可能需要this one基于模板的.phtml扩展名。使用composer安装:

composer require slim/php-view

然后您的控制器方法将执行以下操作:

$view = new \Slim\Views\PhpRenderer('./web/pages');

return $view->render($response, '/hello.phtml');

您最终希望将渲染器放在依赖注入容器中,而不是在控制器方法中创建新实例,但这应该让您开始。

答案 1 :(得分:0)

我通过将渲染器粘贴在容器中来处理此问题。将其粘贴在主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);
   }
}

要清理此代码,请为您创建一个封装了此渲染逻辑的基本处理程序。