Advertisement
kotvalera83

layouts in Slim php framework

Feb 9th, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.95 KB | None | 0 0
  1. layout.php:
  2. <?php
  3. class layout extends Slim_View
  4. {
  5.     static protected $_layout = NULL;
  6.     public static function set_layout($layout=NULL)
  7.     {
  8.         self::$_layout = $layout;
  9.     }
  10.     public function render( $template ) {
  11.         extract($this->data);
  12.         $templatePath = $this->getTemplatesDirectory() . '/' . ltrim($template, '/');
  13.         if ( !file_exists($templatePath) ) {
  14.             throw new RuntimeException('View cannot render template `' . $templatePath . '`. Template does not exist.');
  15.         }
  16.         ob_start();
  17.         require $templatePath;
  18.         $html = ob_get_clean();
  19.         return $this->_render_layout($html);
  20.     }
  21.     public function _render_layout($_html)
  22.     {
  23.         if(self::$_layout !== NULL)
  24.         {
  25.             $layout_path = $this->getTemplatesDirectory() . '/' . ltrim(self::$_layout, '/');
  26.             if ( !file_exists($layout_path) ) {
  27.                 throw new RuntimeException('View cannot render layout `' . $layout_path . '`. Layout does not exist.');
  28.             }
  29.             ob_start();
  30.             require $layout_path;
  31.             $_html = ob_get_clean();
  32.         }
  33.         return $_html;
  34.     }
  35.  
  36. }
  37. ?>
  38. --------
  39. index.php:
  40. <?php
  41. require 'Slim/Slim.php';
  42. require 'layout.php';
  43.  
  44. // instantiate my custom view
  45. $layout = new layout();
  46.  
  47. // seems you need to specify during construction
  48. $app = new Slim(array('view' => $layout));
  49. $app->config(array(
  50.     'templates.path' => './ui',
  51. ));
  52. // specify the a default layout
  53. layout::set_layout('default_layout.php');
  54.  
  55. $app->get('/', function() use ($app) {
  56.     // you can override the layout for a particular route
  57.     // layout::set_layout('index_layout.php');
  58.     $app->render('index.php',array());
  59. });
  60.  
  61. $app->run();
  62. ?>
  63. ------------
  64. default_layout.php:
  65. <html>
  66.     <head>
  67.         <title>My Title</title>
  68.     </head>
  69.     <body>
  70.         <!-- $_html contains the output from the view -->
  71.         <?= $_html ?>
  72.     </body>
  73. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement