Render PHP view scripts into a PSR-7 Response object.

Installs: 1 531 735

Dependents: 91

Suggesters: 2

Stars: 160

Watchers: 13

Forks: 46

Open Issues: 8

2.2.1 2019-04-15 20:43 UTC


Build Status

PHP Renderer

This is a renderer for rendering PHP view scripts into a PSR-7 Response object. It works well with Slim Framework 3.

Cross-site scripting (XSS) risks

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.


Install with Composer:

composer require slim/php-view

Usage with Slim 3

use Slim\Views\PhpRenderer;

include "vendor/autoload.php";

$app = new Slim\App();
$container = $app->getContainer();
$container['renderer'] = new PhpRenderer("./templates");

$app->get('/hello/{name}', function ($request, $response, $args) {
    return $this->renderer->render($response, "hello.php", $args);


Usage with any PSR-7 Project

//Construct the View
$phpView = new PhpRenderer("./path/to/templates");

//Render a Template
$response = $phpView->render(new Response(), "hello.php", $yourData);

Template Variables

You can now add variables to your renderer that will be available to all templates you render.

// via the constructor
$templateVariables = [
    "title" => "Title"
$phpView = new PhpRenderer("./path/to/templates", $templateVariables);

// or setter

// or individually
$phpView->addAttribute($key, $value);

Data passed in via ->render() takes precedence over attributes.

$templateVariables = [
    "title" => "Title"
$phpView = new PhpRenderer("./path/to/templates", $templateVariables);


$phpView->render($response, $template, [
    "title" => "My Title"
// In the view above, the $title will be "My Title" and not "Title"


Inside your templates you may use $this to refer to the PhpRenderer object to render sub-templates.

Rendering in Layouts

You can now render view in another views called layouts, this allows you to compose modular view templates and help keep your views DRY.

Create your layout ./path/to/templates/layout.php.


Create your view template ./path/to/templates/hello.php.

Hello <?=$name?>!

Rendering in your code.

$phpView = new PhpRenderer("./path/to/templates", ["title" => "My App"]);


$phpview->render($response, "hello.php", ["title" => "Hello - My App", "name" => "John"]);

Response will be

<html><head><title>Hello - My App</title></head><body>Hello John!</body></html>

Please note, the $content is special variable used inside layouts to render the wrapped view and should not be set in your view paramaters.


\RuntimeException - if template does not exist

\InvalidArgumentException - if $data contains 'template'