Slim-Documentation icon indicating copy to clipboard operation
Slim-Documentation copied to clipboard

Incorrect instructions for slim/twig-view

Open Mark-H opened this issue 10 years ago • 3 comments

According to http://docs-new.slimframework.com/features/templates/ ("Register the view service"), the code to use is:

// Create Slim app
$app = new \Slim\App();

// Register Twig View service
$app->register(new \Slim\Views\Twig('path/to/templates', [
    'cache' => 'path/to/cache'
]));

However that throws a fatal error Call to undefined method Slim\App::register().

From the readme at https://github.com/slimphp/Twig-View it seems the correct code is actually:

// Create Slim app
$app = new \Slim\App();

// Fetch DI Container
$container = $app->getContainer();

// Register Twig View helper
$container->register(new \Slim\Views\Twig('path/to/templates', [
    'cache' => 'path/to/cache'
]));

.. which seems to at least get rid of the error.

Mark-H avatar Jun 20 '15 22:06 Mark-H

It also looks like

$app->get('/hello/{name}', function ($request, $response, $args) {
    $this['view']->render('profile.html', [
        'name' => $args['name']
    ]);
})->setName('profile');

should be something along the lines of this:

$app->get('/hello/{name}', function ($request, $response, $args) {
    $this->view->render($response, 'profile.html', [
        'name' => $args['name']
    ]);
})->setName('profile');

.. unless I'm being a total noob here, which is totally possible as this is the second time I'm playing with Slim, and the first time was 2.6 too :P

Mark-H avatar Jun 20 '15 22:06 Mark-H

Yeah, if we call:

$this['view']

This return:

Fatal error: Cannot use object of type Slim\App as array

Also add that Twig View extension have 2 methods (fetch and render):

$app->get('/', function($request, $response) {
    $output = $this->view->fetch('index.html', ['name' => 'John']);
    return $response->write($output);
});
$app->get('/', function($request, $response) {
    $this->view->render($response, 'index.html', ['name' => 'John']);
    return $response;
});

It would be desirable get an explanation of their differences

stdex avatar Jul 13 '15 16:07 stdex

jups, array notation is from Pimple, which is the container being used by Slim. Object property notation is from the Slim\App object, which ports to the container.

This is a recent change so could be that the documentation is not up to date yet. Should be solved when Slim 3.0 becomes final.

JoeBengalen avatar Jul 13 '15 17:07 JoeBengalen