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">
<head>
 <title>Example Layout</title>
</head>
<body>

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

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

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

</body>
</html>
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 domain.com/about 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)

Download

 git clone git@github.com:tommymarshall/layouts-with-views.git 
.. 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 is a front-end developer who builds dynamic, interactive sites for Viget clients such as ESPN, Dick's Sporting Goods, and PUMA. He works in our Falls Church, VA, HQ.

More posts by Tommy