sivann
sivann

Reputation: 2131

Slim framework 3 php-view variable

I would like to have a variable from request ($request->getUri()->getBasePath();) always available on the templates. How can I do this e.g. with a middleware without having to pass the above as parameter to renderer->render on all routes each time ?

$app->get(...
   ...
  $args['basepath']=$request->getUri()->getBasePath();
  return $this->renderer->render($response, 'test.php', $args);
});

UPDATE: This can be done after php-view 2.1.0 as so:

dependencies.php:

$container['renderer'] = function ($c) {
    $settings = $c->get('settings')['renderer'];
    return new Slim\Views\PhpRenderer($settings['template_path']);
};

middleware.php:

$app->add(function (Request $request, Response $response, callable $next) {
    $uri = $request->getUri();
    $renderer = $this->get('renderer');
    $renderer->addAttribute('uri', $request->getUri());
    return $next($request, $response);
});

Then, inside the template:

<?php
    $basePath=$uri->getBasePath();
    $rpath=$uri->getPath();
?>

Upvotes: 2

Views: 2720

Answers (2)

Rob Allen
Rob Allen

Reputation: 12778

Version 2.1.0 of PHP-View now supports setting template variables before you render. See https://github.com/slimphp/PHP-View#template-variables.

Upvotes: 2

danopz
danopz

Reputation: 3408

While looking into the Code of the PhpRenderer you will see currently there is no way to specify data outside of the render() function.

You could create an issue and/or make a pull request to support that functionality.

Upvotes: 0

Related Questions