Slim Framework: Partial Views

If you want to use a view partial in the Slim Micro-framework, it’s very easy though may not seem obvious to start with.
The way I solve this is 2-fold: first of all I create a static “Common” class to handle building views, and partial views, allowing me to run:

Common::buildView($response, $this->view, 'index', $viewArgs);

and

Common::getPartialView($this, 'auth_type_field', $data);

The important thing to note here is that we are passing “$this” as the first argument to the partial method. This is significant because at the time of calling the partial, you are likely already in the process of rendering the view, and the context at that point is to your view renderer, whatever that happens to be.

So for me, these methods look like this:

/**
 * Generate a response output wrapped in a layout
 * 
 * @param Response $response
 * @param PhpRenderer $viewRenderer
 * @param string $template
 * @param mixed $viewArgs
 * @return \Slim\Http\Response
 */
public static function buildView(Response $response, PhpRenderer $viewRenderer, $template, $viewArgs = []) {
    // Render the view
    $body = $viewRenderer->fetch($template . '.phtml', $viewArgs);
    
    // Render the layout
    $header = $viewRenderer->fetch('layout/header.phtml', $viewArgs);
    $content = $viewRenderer->fetch('layout/content.phtml', ['content' => $body]);
    $footer = $viewRenderer->fetch('layout/footer.phtml', $viewArgs);
    
    // Combine layout and view
    $output = $header . $content . $footer;
    
    // Write and return the response
    $response->getBody()->write($output);
    return $response;
}

/**
 * Fetch a partial template, useful for table rows etc
 * 
 * @param PhpRenderer $viewRenderer
 * @param string $template
 * @param array $viewArgs
 * @return mixed
 */
public static function getPartialView(PhpRenderer $viewRenderer, $template, $viewArgs = []) {
    $partial = $viewRenderer->fetch('partials/' . $template . '.phtml', $viewArgs);
    return $partial;
}

As you can see, I still use my view renderer to fetch the template as normal, and pass it my view args as normal.

HTH

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.