Slim does not have a view layer like traditional MVC frameworks. Instead, Slim’s “view” is the HTTP response. Each Slim application route is responsible for preparing and returning an appropriate PSR-7 response object.
Slim’s “view” is the HTTP response.
That being said, the Slim project provides the Twig-View and PHP-View components to help you render templates to a PSR7 Response object.
The Twig-View PHP component helps you render Twig templates in your application. This component is available on Packagist, and it’s easy to install with Composer like this:
Next, you need to add the slim/twig-view middleware to the Slim app:
Note: For production scenarios, cache
should be set to some 'path/to/cache'
to store compiled templates (thus avoiding recomplication on every request).
For more information, see Twig environment options
Now you can use the slim/twig-view
component service inside an app route to render a template and write it to a PSR-7 Response object like this:
In this example, $view
invoked inside the route callback is a reference to the \Slim\Views\Twig
instance returned by the fromRequest
method.
The \Slim\Views\Twig
instance’s render()
method accepts a PSR-7 Response object as its first argument, the Twig template path as its second argument, and an array of template variables as its final argument.
The render()
method returns a new PSR-7 Response object whose body is the rendered Twig template.
The slim/twig-view
component exposes a custom url_for()
function to your Twig templates.
You can use this function to generate complete URLs to any named route in your Slim application.
The url_for()
function accepts two arguments:
The second argument’s keys should correspond to the selected route’s pattern placeholders. This is an example Twig template that draws a link URL for the “profile” named route shown in the example Slim application above.
{% extends "layout.html" %}
{% block body %}
<h1>User List</h1>
<ul>
<li><a href="{{ url_for('profile', { 'name': 'josh' }) }}">Josh</a></li>
</ul>
{% endblock %}
The PHP-View PHP component helps you render PHP templates. This component is available on Packagist and can be installed using Composer like this:
You can use it with Slim like this:
You are not limited to the Twig-View
and PHP-View
components.
You can use any PHP template system provided that you ultimately write the rendered template output to the PSR-7 Response object’s body.