Shahzaib Idrees Baluch Shahzaib Idrees Baluch - 1 year ago 69
PHP Question

phpSlim twg-view not working

i am getting error in my slim framework application. i don't know why twig-view is not working. twig-view is downloaded in vendor directory.
this is my index file

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(


return $view;

// Home

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


i am getting error om $this keyword
error details


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

Answer Source

You are declaring route incorectly, try

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

Instead of declaring a function, you should call $app method to register a route.


It is also possible to "separate" route declaration from the callback. You can create separate classes (a-la controllers in MVC pattern), like this:

// 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');

I suggest you read the appropriate section of the documentation. It's dead simple.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download