02 - Chunking up the Main Template into a Collection of Embedded Templates

In this chapter we start what I’ve been calling the “chunking up” of the template, where we take chunks of the HTML code from the master template, save them off as embedded EE templates, and add the embed code back to the master EE template.

Download the EE Code for 02 - Chunking up the Main Template into a Collection of Embedded Templates

Why Embedded Templates?
For those new to ExpressionEngine and embedding templates, you might first want to peruse the help documentation on embedded templates (although that page doesn’t talk much about the benefits of embedding templates).

The overall goal of the chunking up process is to only store common/reusable elements in one place in EE - both for ease of constructing the site and ease of future changes or maintenance.

This way when you want to add a new section to your site and need to add it to the main navigation, you only need make that change in one EE template.  Since that template is embedded into the rest of the site, your change is immediately reflected across the entire site.  If you have experience with server includes, it’s a very similar design approach.

What to Embed?
Before delving into the code, though, we should step back and take a look at the current page and what we’re intending to do.  Sometimes I can get carried away with the chunking up and end up with a site that’s more complex than it needs to be.  The big question is what elements (both from a visual and coding perspective) would benefit from being embedded?  Starting visually, the obvious candidates are anything that’s sure to be repeated as we move through the site:

  • The company name / logo
  • The main navigation
  • The search box
  • The footer

We can add the Latest News and Latest Products blocks to that list—as we can then promote them on multiple pages throughout the site.  The Register Now box is interesting - but the way it’s positioned in the middle of other content will make it difficult to embed.  Let’s just lose that box as there will be no need for it on this site.

Looking at the source code on the HTML, we’ll also grab the HTML header including meta tags, the link to the stylesheet, and page title.  I know—the page title needs to be different with each page. In a future chapter I’ll show you how to keep the page title stored in the embedded template, but also have each page get a unique title.

Chunking Plan
Note: In the attached files for this chapter you’ll find a copy of the index HTML with comments added to denote where the code will be chunked up.  If you open the file in a text or HTML editor and peruse the code, you’ll note the large amount of content that isn’t being pulled out and embedded.  That’s the core content of the page and, in the next chapter of this series, will get pulled out of the template and stored in an EE weblog.

I’m sure different EE developers do this differently.  I prefer to keep the skeleton of the page’s essential structure in the parent template.  I don’t like having div tags getting opened in one template and closed in another as it has made it hard to track down mis-matches or validation errors.

Create a New Template Group
I like to keep all my embedded templates in their own group, so that my main groups hold the parent templates.  Here are the steps:

  • Enter the EE Control Panel.
  • Click Templates tab.
  • Click Create a New Template Group button on the upper right portion of the screen.
  • Choose a name.  I’ve called mine “embeds”.
  • Click Submit.

On to the Chunking!
I like to do this step incrementally - so my basic workflow is:

  • With the full index template open, copy the section of code I want to embed.
  • Create a new template in my “embeds” group.
  • Choose None- Create an Empty Template option, name the template, and click Submit.
  • Click on the new template title to edit it.
  • Paste in the section of code.
  • Adjust any formatting.
  • Click Update.
  • Don’t leave this screen just yet - up in the title area just over the editable text area EE provides the name of the template along with the Template Group name - for example; “embeds/html_header”.
  • Select and copy this to the clipboard.
  • Return to the master site/index template in edit mode.
  • Select the same portion of code that you copied earlier.
  • Do a paste, so that chunk of code is replaced with the name and Template Group of your new embedded template - again the example “embeds/html_header”.
  • Add the EE embedding code, so “embeds/html_header” becomes embed=“embeds/html_header”.
  • Save the master template by clicking Update.
  • Click View Rendered Template button to ensure that the master template remains unchanged visually. Sometimes I’ve grabbed one line of code too many or too little and this is where I catch those mistakes.
  • Repeat the above process for each section of code in the chunking plan file.

After Chunking
You should have an “embeds” Template Group with the following templates:

  1. footer
  2. html_header
  3. latest_news
  4. latest_products
  5. logo_title
  6. main_nav
  7. search_section_intros

There are text versions of each of these templates in the attached files.

You should now also have a drastically simplified site/index template, with all the repeatable elements pulled out and embedded back in.  Here’s what I have:

Template Name: site/index

div id="content">

<div id="maincontent">
div id="right_side">
</div><!-- close right_side -->

div id="left_side">
h2 class="underline">Abous us</h2>
img src="{site_url}/images/interface/img.jpg" alt="image" />
p><strong>Lorem ipsum dolor</strongsit ametconsectetuer adipiscing elitMorbi elementumipsum nec auctor condimentummagna odio aliquet elitnon bibendum lorem ligula at nisiProin sapienIn hac <a href="#" title="">habitasse platea dictumst</a>. Nunc non magnaDuis pharetra laoreet dolorMauris tristique interdum turpisPraesent sed pedeAenean porttitor ultrices tortorAenean a purusPraesent eu sapien.</p>

p>Nulla posueresapien sit amet euismod suscipitmagna diam sodales magnanec semper eros tortor et nullaNunc nec maurisAenean tinciduntNam semEtiam quis justoDonec pellentesque pellentesque tellus. <strong>Integer bibendum</strongmassa sed diamIn in elitUt blandit arcu sed ligulaAenean interdumSuspendisse adipiscing suscipit nislIn non leo et justo posuere placeratIn tincidunt cursus turpisMaecenas suscipit tempor anteVestibulum pretium aliquam metus.</p>

blockquote><class="mpnull">Sapien sit amet euismod suscipitmagna diam sodales magnanec semper eros tortor et nullaNunc nec maurisAenean tinciduntNam semEtiam quis justoDonec pellentesque pellentesque tellus. <strong>Integer bibendum</strongmassa sed diamIn in elit.</p></blockquote>
p>Nulla posueresapien sit amet euismod suscipitmagna diam sodales magnanec semper eros tortor et nullaNunc nec maurisAenean tinciduntNam semEtiam quis justoDonec pellentesque pellentesque tellus. <strong>Integer bibendum</strongmassa sed diam. </p>

div class="textbox">
h2><a href="#" title="">Register now!</a></h2>
p>Nulla posueresapien sit amet euismod suscipitmagna diam sodales magnanec semper eros tortor et nullaNunc nec mauris.</p>
p>Lorem ipsum dolor sit ametconsectetuer adipiscing elitMorbi <a href="#" title="">elementum</a>, ipsum nec auctor condimentummagna odio aliquet elitnon bibendum lorem ligula at nisiProin sapienIn hac habitasse platea dictumst.</p>

h2>Our Assets</h2>
p>In hac habitasse platea dictumstNunc non magnaDuis pharetra laoreet dolorMauris tristique interdum turpisPraesent sed pedeAenean porttitor ultrices tortorAenean a purusPraesent eu sapien.</p>
p>In hac habitasse platea dictumstNunc non magnaDuis pharetra laoreet dolor.</p>
li>In hac <strong>habitasse</strongplatea dictumst</li>
li>Lorem ipsum dolor <a href="#" title="">sit amet</a></li>
li>habitasse platea dictumst</li>
li>sapien sit amet euismod</li>
div><!-- close left side div -->
div><!-- close main content div -->
</div>    <!-- close content div -->

The Results
Once you have all these template changes made and saved, you should be able to load the rendered version of the site/index template and have it appear exactly as it did at the end of Chapter 1.


Category Navigation

<< Previous Entry   

Next Entry >>


Previous Comments

Picture of David Siembab

by David Siembab

Date: Sunday, November 30th, 2008
Comment: #1

nice thanks a lot man. I thought it would be simple. Thanks again

Picture of Jason Hudnutt

by Jason Hudnutt

Date: Friday, December 5th, 2008
Comment: #2

I love your tutorials! Although I prefer to hide the embeds by naming the file .footer and calling it as {embed=“embeds/.footer”}. I think that is just a personal opinion so just in case a user navigates to an embed it will not show.

Mike Boyink

by Mike Boyink (Author)

Date: Friday, December 26th, 2008
Comment: #3

It gets left empty.

Picture of Trench

by Trench

Date: Wednesday, November 11th, 2009
Comment: #4

This seems opposite to what make most sense to me.  There should be a central layout and/or wrapper that embeds the proper page templates.  You don’t want to have to maintain ‘embed code’ on every page.  Thoughts?

Mike Boyink

by Mike Boyink (Author)

Date: Wednesday, November 11th, 2009
Comment: #5

Well, yea.

First - you’re not maintaining embed code on every page.  It’s just on every template.  Big difference.  Regardless of the number of pages on a given site most of my EE builds have < 20 templates, and the embed structure rarely, if ever, has changed. And even if it had to it would only take a few minutes to run through those templates and make the updates. You could possibly even use EE’s Find and Replace function.

Second - you can push EE that way if you want to - check out this writeup

The issue I see with that approach is alot of added logic and at least another layer of embeds,  which starts to go against many of the performance guidelines (PDF) written for EE.

You also have to balance the benefit of possible time savings in the future with known longer development times (and a harder-to-reverse-engineer backend structure) now. 

It’s easy to be penny-wise and pound-foolish when it comes to development work like this, and spend hours figuring out some cleverly programmed solution that only ever ends up saving you a few minutes down the road. 

That said - the approach I’ve developed and detail here is what works for me, with my typical clients & projects, with the benefit of 5 years of EE experience.  It’s certainly not my position that this approach is correct or preferable to everyone (I’ll rarely claim that anything I cover here on Train-ee is a “best practice”)..;)

Picture of Trench

by Trench

Date: Wednesday, November 11th, 2009
Comment: #6

Matt - Your absolutely right about the form versus function tradeoff.  Thanks for the reference to the other method.  It certainly does get convoluted.  I am just used to the MVC pattern of controllers directing traffic and passing variables to a view. 

WIth that said, I will check out the performance guidelines and reconsider based on your experience with the framework.

BTW, these tutorials are incredible resources.  Thanks for making this available!

Mike Boyink

by Mike Boyink (Author)

Date: Wednesday, November 11th, 2009
Comment: #7

Hey Trench -

As EE and CI get closer together it should be interesting - you aren’t the first CI guy to come to EE and get a bit weirded out by the templating approach.

I think it’s important to keep in mind that EE isn’t really an MVC framework although it starts to look like one in spots and it was the genesis of CI.

I hope to learn more about CI in the coming year—I’m not able to fully explain EE in the context of it because I don’t know CI, and have not programmed using an MVC -based framework of any sort.

Picture of Alberto

by Alberto

Date: Friday, March 26th, 2010
Comment: #8

Hi Mike, thank’s for this tutorials, I’m learning a lot!

Just a tip to anyone who’s having problem’s with the embed code.

In my case {embed=“embeds/header”} didn’t work, I tried a lot of stuff’s untill I replaced the ” ” for ’ ‘, and that fixed the problem.

Thanks again!

Picture of Richard

by Richard

Date: Friday, August 6th, 2010
Comment: #9

this tutorial is invaluable, but how do I use meta-tags for each individual page when I have chunked up my data like this, as I cannot see how I can insert the tags into the html header.

Many thanks for providing by far and away the best EE tutorials by a mile!!

Mike Boyink

by Mike Boyink (Author)

Date: Friday, August 6th, 2010
Comment: #10

Keep reading…;)  Look for Embed Variables for Embedded Templates.

Picture of Richard

by Richard

Date: Friday, August 6th, 2010
Comment: #11

ok will do!  half the problem with EE is knowing what the correct term is for what you are after :)

many thanks.

Picture of Graham

by Graham

Date: Tuesday, August 10th, 2010
Comment: #12

How would you alter this page to make use of the “Snippets” code now available in EE 2.0? And, can variables be passed into snippets the same way they can into embedded templates?

Mike Boyink

by Mike Boyink (Author)

Date: Wednesday, August 11th, 2010
Comment: #13

Having said that - essentially I used Snippets where I didn’t need the fuller power of Embedded Templates.

Mike Boyink

by Mike Boyink (Author)

Date: Wednesday, August 11th, 2010
Comment: #14

Hey Graham -

First, at the risk of being “that guy” I will point out that last Friday I released the updated book version of this series, which covers the differences between global variables, snippets, and embedded templates in detail.  It also covers how I would chunk up this page using snippets.  The details on the book are here.

The EE docs have a section on “how to choose between an Embedded Template and Snippet” section on the page for Embedded Templates—that section along with the Snippet-specific page are a good primer on using them.

Picture of christopher

by christopher

Date: Friday, January 21st, 2011
Comment: #15

First things first—THANK YOU!!!  For taking the time to produce these tutorials!

I’m reading through, and trying to learn EE, and curious to know—in the chunking/embedding process, do you also copy and paste the <div> </div> codes into the new templates to be embedded??  ...Or ONLY the code?

Thank you in advance.

Picture of Boyink

by Boyink

Date: Friday, January 21st, 2011
Comment: #16

Hey Christopher:

I usually leave a skeleton of HTML in the parent template, but also will chunk out lower-level div tags if it makes sense. 

I try to keep things matched regardless - so divs get opened and closed in the same template.

Add Your Comment

Commenting is not available in this channel entry.

Unless otherwise stated all content is © Michael Boyink of Train-ee.com & Boyink Interactive. Please don't steal - I've got kids to feed...