This is a renderer for rendering PHP view scripts into a PSR-7 Response object. It works well with Slim Framework 3.
Note that PHP-View has no built-in mitigation from XSS attacks. It is the developer's responsibility to use htmlspecialchars() or a component like zend-escaper. Alternatively, consider Twig-View.
You may use $this inside your php templates. $this will be the actual PhpRenderer object will allow you to render sub-templates
Install with Composer:
composer require slim/php-view useSlim\Views\PhpRenderer; include"vendor/autoload.php"; $app = newSlim\App(); $container = $app->getContainer(); $container['renderer'] = newPhpRenderer("./templates"); $app->get('/hello/{name}', function ($request, $response, $args){return$this->renderer->render($response, "/hello.php", $args)}); $app->run();//Construct the View$phpView = newPhpRenderer("./path/to/templates"); //Render a Template$response = $phpView->render(newResponse(), "/path/to/template.php", $yourData);You can now add variables to your renderer that will be available to all templates you render.
// via the constructor$templateVariables = [ "title" => "Title" ]; $phpView = newPhpRenderer("./path/to/templates", $templateVariables); // or setter$phpView->setAttributes($templateVariables); // or individually$phpView->addAttribute($key, $value);Data passed in via ->render() takes precedence over attributes.
$templateVariables = [ "title" => "Title" ]; $phpView = newPhpRenderer("./path/to/templates", $templateVariables); //...$phpView->render($response, $template, [ "title" => "My Title" ]); // In the view above, the $title will be "My Title" and not "Title"\RuntimeException - if template does not exist
\InvalidArgumentException - if $data contains 'template'