Custom

A Slim application delegates rendering of templates to its view object. A custom view is a subclassof \Slim\View that implements this interface:

  1. <?php
  2. public render(string $template);

The view object’s render method must return the rendered content of the template specified by its$template argument. When the custom view’s render method is invoked, it is passed the desired templatepathname (relative to the Slim application’s “templates.path” setting) as its argument. Here’s an examplecustom view:

  1. <?php
  2. class CustomView extends \Slim\View
  3. {
  4. public function render($template)
  5. {
  6. return 'The final rendered template';
  7. }
  8. }

The custom view can do whatever it wants internally so long as it returns the template’s rendered output as a string.A custom view makes it easy to integrate popular PHP template systems like Twig or Smarty.

Heads Up! A custom view may access data passed to it by the Slim application’s render() method with $this->data.

You can browse ready-to-use custom views that work with popular PHP template engines in the Slim-Extras repositoryon GitHub.

Example View

  1. <?php
  2. class CustomView extends \Slim\View
  3. {
  4. public function render($template)
  5. {
  6. // $template === 'show.php'
  7. // $this->data['title'] === 'Sahara'
  8. }
  9. }

Example Integration

If the custom view is not discoverable by a registered autoloader, it must be required before the Slim applicationis instantiated.

  1. <?php
  2. require 'CustomView.php';
  3. $app = new \Slim\Slim(array(
  4. 'view' => new CustomView()
  5. ));
  6. $app->get('/books/:id', function ($id) use ($app) {
  7. $app->render('show.php', array('title' => 'Sahara'));
  8. });
  9. $app->run();