Header/footer in php-view with Slim v3

What is the recommended way to add header/footer to all views with php-view? I’m trying to create a middleware, but getting error what $app doesn’t have a render function:

<?php use Psr\Http\Message\RequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; $app->add(function (Request $req, Response $res, callable $next) use ($app) { $app->render($res, 'header.php', []); $newResponse = $next($req, $res); $app->render($res, 'footer.php', []); return $newResponse; // continue });

I haven’t tested this but you should be able to do:

<?php

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $request, Response $response, callable $next) {
    $renderer = $this->container->get('renderer'); // or maybe its $this->get('renderer');
    $response = $renderer->render($response, 'header.php');
    $response = $next($request, $response);
    $response = $renderer->render($response, 'footer.php');
    
    return $response;
});

Yay! That sort of worked :slight_smile: This is the working code:

<?php
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $request,  Response $response, callable $next) use ($app) {
  $renderer = $app->getContainer()->get('renderer'); 
  $response = $renderer->render($response, 'header.php');
  $response = $next($request, $response);
  $response = $renderer->render($response, 'footer.php');

  return $response;
});

You don’t need to pass $app with a use, you can do as in my example above but do $this->get('renderer') instead. The container is bound to any closure used as a middleware.