Templates

Slim does not have a view layer like traditional MVC frameworks. Instead,Slim’s “view” is the HTTP response. Each Slim application route is responsiblefor 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 andPHP-View components to help you render templates to a PSR7Response object.

The slim/twig-view component

The Twig-View PHP component helps you render Twigtemplates in your application. This component is available on Packagist, andit’s easy to install with Composer like this:

  1. composer require slim/twig-view
Figure 1: Install slim/twig-view component.

Next, you need to register the component as a service on the Slim app’scontainer like this:

  1. <?php
  2. // Create app
  3. $app = new \Slim\App();
  4. // Get container
  5. $container = $app->getContainer();
  6. // Register component on container
  7. $container['view'] = function ($container) {
  8. $view = new \Slim\Views\Twig('path/to/templates', [
  9. 'cache' => 'path/to/cache'
  10. ]);
  11. // Instantiate and add Slim specific extension
  12. $router = $container->get('router');
  13. $uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
  14. $view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
  15. return $view;
  16. };
Figure 2: Register slim/twig-view component with container.

Note : “cache” could be set to false to disable it, see also ‘auto_reload’ option, useful in development environment. For more information, see Twig environment options

Now you can use the slim/twig-view component service inside an app routeto render a template and write it to a PSR-7 Response object like this:

  1. // Render Twig template in route
  2. $app->get('/hello/{name}', function ($request, $response, $args) {
  3. return $this->view->render($response, 'profile.html', [
  4. 'name' => $args['name']
  5. ]);
  6. })->setName('profile');
  7. // Run app
  8. $app->run();
Figure 3: Render template with slim/twig-view container service.

In this example, $this->view invoked inside the route callback is a referenceto the \Slim\Views\Twig instance returned by the view container service.The \Slim\Views\Twig instance’s render() method accepts a PSR-7 Responseobject as its first argument, the Twig template path as its second argument,and an array of template variables as its final argument. The render() methodreturns a new PSR-7 Response object whose body is the rendered Twig template.

The path_for() method

The slim/twig-view component exposes a custom path_for() functionto your Twig templates. You can use this function to generate completeURLs to any named route in your Slim application. The path_for()function accepts two arguments:

  • A route name
  • A hash of route placeholder names and replacement valuesThe second argument’s keys should correspond to the selected route’s patternplaceholders. This is an example Twig template that draws a link URLfor the “profile” named route shown in the example Slim application above.
  1. {% extends "layout.html" %}
  2. {% block body %}
  3. <h1>User List</h1>
  4. <ul>
  5. <li><a href="{{ path_for('profile', { 'name': 'josh' }) }}">Josh</a></li>
  6. </ul>
  7. {% endblock %}

Extending twig

Twig can be extended with additional filters, functions, global variables, tagsand more.

To register a filter, add the following after registering the view componentwith the container:

  1. $filter = new Twig_SimpleFilter('rot13', function ($string) {
  2. return str_rot13($string);
  3. });
  4. $container->get('view')->getEnvironment()->addFilter($filter);
Figure 4: Registering a filter with Twig

This adds a “rot13” filter to twig:

  1. {# outputs "Slim Framework" #}
  2. {{ 'Fyvz Senzrjbex'|rot13}}

To register a function, add the following after registering the view componentwith the container:

  1. $function = new Twig_SimpleFunction('shortest', function ($a, $b) {
  2. return strlen($a) <= strlen($b) ? $a : $b;
  3. });
  4. $container->get('view')->getEnvironment()->addFunction($function);
Figure 5: Registering a function with Twig

This adds a “shortest” function to twig:

  1. {# outputs "Slim" #}
  2. {{ shortest('Slim', 'Framework') }}

The twig documentationcontains more details on Twig extensions.

The slim/php-view component

The PHP-View PHP component helps you render PHP templates.This component is available on Packagist and can be installed usingComposer like this:

  1. composer require slim/php-view
Figure 6: Install slim/php-view component.

To register this component as a service on Slim App’s container, do this:

  1. <?php
  2. // Create app
  3. $app = new \Slim\App();
  4. // Get container
  5. $container = $app->getContainer();
  6. // Register component on container
  7. $container['view'] = function ($container) {
  8. return new \Slim\Views\PhpRenderer('path/to/templates/with/trailing/slash/');
  9. };
Figure 7: Register slim/php-view component with container.

Use the view component to render a PHP view like this:

  1. // Render PHP template in route
  2. $app->get('/hello/{name}', function ($request, $response, $args) {
  3. return $this->view->render($response, 'profile.html', [
  4. 'name' => $args['name']
  5. ]);
  6. })->setName('profile');
  7. // Run app
  8. $app->run();
Figure 8: Render template with slim/php-view container service.

Other template systems

You are not limited to the Twig-View and PHP-View components. Youcan use any PHP template system provided that you ultimately write the renderedtemplate output to the PSR-7 Response object’s body.