Simplify your build-out process using Layouts with Views

I recently found myself building out a comp which seemed to have only enough code repetition to include a header and footer. However, the further I got into build-out the more code repetition emerged. I saw an opportunity for a MVC-like views system to help, so I set out to build one to make my build-out process easier.

Code Examples

Let's say you have a basic layout with a reusable header and footer, like the one in the example below. 

 <!-- location: views/layouts/default.php -->
<html lang="en">
 <title>Example Layout</title>

 <?php $this->render('shared/header'); ?>

 <div class="content">
 <?php $this->getContent(); ?>

 <?php $this->render('shared/footer'); ?>

This default layout is rendering a header and footer file located in the views/shared/ directory. Now, if we wanted to create an About page with some content that uses this default layout, we would do something like this:
 <!-- location: views/about.php -->
<?php $this->layout('default'); ?>

<h2>About Page</h2>

<p>Lorem ipsum dolor copy.</p>

If we opened in the browser, we would see the About page content loaded within the default layout we created above. (Note: In the above example we could lose the layout declaration at the top since Layouts with Views expects to load default.php as the default layout. This setting can be changed in settings/config.php.)

The above example shows a basic application of Layouts with Views. Check out the Github page for examples of features like:

  • Multiple layouts
  • Nested views
  • Passing variables to views
  • Allow for common control structures (if, foreach, etc.)
  • Referencing page assets (images, stylesheets) using an absolute path
  • Simple routing (Create the file, done)


 git clone 
.. or click here to download a zip.

In Conclusion

Layouts with Views sets out to solve a small problem and that's it. There's no customizable routing, no crazy templating features, no unusal syntax to learn. It’s just a simple way for me to build out comps. That's what I like about it.


Tommy Marshall

Posted in Article Category: #Code