Rendering Templates - rougin/slytherin GitHub Wiki
← Using PSR Interfaces | Creating Middlewares →
Slytherin does not provide an implementation regarding the template layer as the PHP language itself is a template engine. Instead, whatever is being returned in an HTTP route, Slytherin converts it into a HTTP response (ResponseInterface) object. Returning HTTP responses from HTTP requests makes Slytherin more flexible in integrating on third-party template engines:
// app/web/index.php
// ...
$app->get('/', function ()
{
return 'Hello <b>world</b>!';
});
// ...Opening the link below should return a text Hello world with the world displayed in bold text:
http://localhost:8000
If there is a need to use a template engine, with the purpose to escape values or to separate the presentation layer from its business logic, Slytherin provides a simple templating interface using the RendererInterface that can be used inside the HTTP route.
To initialize the template renderer, kindly create a new file named hello.php in the app/plates directory then paste the following HTML code:
<!-- app/plates/hello.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>Hello <b><?php echo $name; ?></b>!</p>
</body>
</html>From the main index.php file, initialize the Renderer instance with the path of the templates to be used:
// app/web/index.php
use Rougin\Slytherin\Template\Renderer;
use Rougin\Slytherin\Template\RendererInterface;
// ...
// Initialize the Renderer instance ---
$paths = array($root . '/app/plates');
$renderer = new Renderer($paths);
// ------------------------------------
// Add the Renderer to the container ----------------
$container->set(RendererInterface::class, $renderer);
// --------------------------------------------------
// ...
$app->get('/', function (RendererInterface $view)
{
$data = array('name' => 'Slytherin');
return $view->render('hello', $data);
});
// ...Refreshing the same page from the web browser based on the previous section should return a text Hello Slytherin! with the Slytherin text displayed in bold.
Tip
Check the Template documentation under Components to check alternative implementations for the RendererInterface.