php Slim twig-view 不工作

phpSlim twg-view not working

我的 slim 框架应用程序出现错误。我不知道为什么 twig-view 不起作用。 twig-view 在供应商目录中下载。 这是我的索引文件

<?php
require  __DIR__ . '/vendor/autoload.php';
// Settings
$config = [
    'settings' => [
        'displayErrorDetails' => true,
        'addContentLengthHeader' => false,
    ],
];

$app = new \Slim\App($config);

// Get container
$container = $app->getContainer();

// Register component on container
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig( __DIR__ . '/resources/views', [
        'cache' => false
    ]);

    // Instantiate and add Slim specific extension

    $view->addExtension(new Slim\Views\TwigExtension(
    $container['router'],
    $container['request']->getUri()

    ));

    return $view;
};

// Home
$app->get('/home','index');



function index($request, $response, $args)
{
   return $this->view->render($response, 'home.twig'); // here is the error 
}

$app->run();

我收到 $this 关键字错误 错误详情

Details

Type: Error
Message: Using $this when not in object context
File: C:\xampp\htdocs\slim\api\index.php
Line: 42

您正在错误地声明路线,尝试

// This callback will process GET request to /index URL    
$app->get('/index', function($request, $response, $args) {
    return $this->view->render($response, 'home.twig');
});

您应该调用 $app 方法来注册路由,而不是声明一个函数。

编辑

也可以 "separate" 从回调中路由声明。您可以创建单独的 类(MVC 模式中的 a-la 控制器),如下所示:

// Declaring a controller class with __invoke method, so it acts as a function
class MyController
{

    public function __invoke($request, $resposne)
    {
        // process a request, return response
    }

}

// And here's how you add it to the route
$app->get('/index', 'MyController');

我建议你阅读appropriate section of the documentation。非常简单。

没有闭包时无法使用此功能

If you use a Closure instance as the route callback, the closure’s state is bound to the Container instance. This means you will have access to the DI container instance inside of the Closure via the $this keyword.

(参考:http://www.slimframework.com/docs/objects/router.html

当你把闭包赋值给一个变量时,你可以把它分开

$indexRoute = function ($request, $response, $args)
{
    return $this->view->render($response, 'home.twig'); // here is the error 
}

$app->get('/home', $indexRoute);