Skip to content

Views, Partials and Layouts

Nathan edited this page Jan 6, 2015 · 3 revisions

Layouts and Views

When creating HTML files I prefer to use PHP's templating syntax: Instead of writing <?php echo $this->pageTitle; ?>, you can write <?= $this->pageTitle; ?> instead. Another point to remember is when echoing data, you should always escape it.

layouts/default.php

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8">
        <title><?= $this->escape($this->pageTitle); ?></title>
    </head>
    <body>
        <header><h1>My Awesome Site</h1></header>
        <section role="main">
            <?= $this->yieldView(); ?>
        </section>
        <footer><small>Copyright &copy; <?= date('Y') ?>, My Awesome Site</small></footer>
    </body>
</html>

And below is our view file.

views/home.php

<p>Hello World!</p>

Finally, let's piece everything together.

bootstrap.php

<?php

// all requests are redirected to this file.
// use your .htaccess file to set this up.

error_reporting(-1);
require_once 'klein.php/vendor/autoload.php';

$klein = new Klein\Klein;

// First, let's setup the layout our site will use. By passing 
// an anonymous function in Klein will respond to all methods/URI's.
$klein->respond(function ($request, $response, $service) {
    $service->layout('layouts/default.php');
});

// Home page view
$klein->respond('/', function ($request, $response, $service) {
    // add some data to the view.
    $service->pageTitle = 'Home page';

    // This is the function that renders the view inside the layout.
    $service->render('views/home.php');
});

$klein->dispatch();

And that's it!

Partials

Partials are individual snippets of HTML/PHP. Adding a partial is easy.

Let's take the above example and turn the header and footer into a partial.

layouts/default.php

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8">
        <title><?= $this->pageTitle; ?></title>
    </head>
    <body>
        <?= $this->partial('partials/header.php'); ?>
        
        <section role="main">
            <?= $this->yieldView(); ?>
        </section>

        <?= $this->partial('partials/footer.php'); ?>
    </body>
</html>

The header.php partial will now contain the following HTML:

<header><h1>My Awesome Site</h1></header>

And in the footer.php partial:

<footer><small>Copyright &copy; <?= date('Y') ?>, My Awesome Site</small></footer>
Clone this wiki locally