Search code examples
phpslimmiddleware

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();
?>

Solution

  • 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.