Skip to content

Instantly share code, notes, and snippets.

@evansims
Last active May 20, 2020 19:27
Show Gist options
  • Save evansims/5131474 to your computer and use it in GitHub Desktop.
Save evansims/5131474 to your computer and use it in GitHub Desktop.
An example of automatically including header and footer templates using Slim hooks.
$app->hook('slim.before.dispatch', function () use ($app) {
$app->render('/views/header.php');
});
$app->hook('slim.after.dispatch', function () use ($app) {
$app->render('/views/footer.php');
});
require_once 'slim/Slim.php';
$app = new Slim();
require 'hooks.php';
require 'routes.php';
$app->run();
$app->get('/users/:id/?', function ($id) use ($app) {
$app->render('/views/user_profile.php', array('id' => $id));
});
@ccfelix
Copy link

ccfelix commented Sep 17, 2015

Thanks!!! Great tip for templating with Slim Framework.

@lenichols
Copy link

Brilliant... just gave this a try and it works like a charm... i did have to add the following to work with my deployment:

instead of: $app->render('./templates/header.php'); which didn't work because slim was looking for the TemplatesDirectory as I am not using twig or any of the templating engines...

i used:

    $view = $app->view();
$view->setTemplatesDirectory('./templates/');
$app->render('./header.php');

along with your dispatch methods and it worked perfectly! thanks...

@eldinphp
Copy link

Very helpful, thanks

@Gegengift
Copy link

Gegengift commented Feb 8, 2018

There are no hooks in Slim 3.
Use middleware instead of hooks for Slim 3 https://www.slimframework.com/docs/start/upgrade.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment