Snippets or Embedded Templates?

Ever since ExpressionEngine 2 went release with Snippets I’ve been wanting to do some comparison between them and other coding approaches.

 

What are Snippets?
The short answer is they are the EE 1x Fresh Variables renamed, brought into the application by default, and given a more prominent place in the Control Panel.

The longer answer from the documentation page linked to above:

Snippets are small bits of reusable template or tag parts. You could create a Snippet for any number of purposes, anywhere that you need to reuse a small portion of a template, including partial or complete tags, other variables, etc. Snippets add flexibility and reusability, while making it simple to make site-wide changes by editing the Snippet’s source instead of having to modify many templates.

Well, yea, nothing new here, right?  We’ve always had the ability to save a chunk of code as an embedded template and use it over and over.  But go back and read that again.  Snippets can contain partial tags.  This is new - with embedded templates you always need to code complete tag pairs in the template to be embedded in - you can’t for example, have the calling template contain the opening exp:channel:entries tag and then store the closing /exp:channel:entries tag in the embedded template.

The key to this added flexibility is the parse order, or the order in which ExpressionEngine reads and executes the code you create in templates:

Snippets are expanded at a very early stage on each template, making it possible for them to hold dynamic content, ExpressionEngine tags, other variables, PHP, etc. They shine when you need to reuse dynamic information, but don’t need the extra overhead of access control or separate preferences of an embedded template.

In addition to the sample ideas in the docs, I wanted to explore Snippets in a different way.

A Different Coding Approach?
Ever since getting familiar with Snippets I’ve been wondering if there are ways to use Snippets in place of Embedded Templates with Embed Variables, and what advantages & disadvantages there might to doing so.

One way I commonly use Embed Templates with Embed Variables is building sidebar content.  Sites often have lists of things in the sidebar - most recent entries, most recent comments, etc.  Many times these lists are very similar, only differing in what channel the items are being pulled from. In these cases I’ll create one embedded template and pass in the channel name as an embed variable - so I can centralize the logic and markup of the list but still dictate which results I get in the parent template.  This seemed like a good test case for a Snippet-based approach instead.  Below are the two coding approaches presented and then an analysis of rendering time, memory and queries used.

The Embedded Template Approach
Here is the code for my parent template:

<h1>Test Embedded Templates with Embed Variables</h1>
<
p>The following two lists are returned using one embedded template, and passing embed variables  to get different results.</p>

{embed="embeds/latest_entries" my_channel="salads" my_path="salads"}

{embed
="embeds/latest_entries" my_channel="restaurants" my_path="restaurants"

And then here is the code for the embedded template:

<h5>Latest {embed:my_title}</h5>
{exp:channel:entries 
    channel
="{embed:my_channel}" 
    
limit="5" disable="custom_fields|categories|member_data|pagination" 
    
dynamic="no"
    
}

    {if count
==1}
        
<ul>
    
{/if}

    
<li>{title}</a></li>

    
{if count==total_results}
        
</ul>
    
{/if}
{
/exp:channel:entries} 

What I like about this template is the parent template is very clean.  The embedded template is called in twice but passed different values in the embed variables to get different lists as results.  The programmer in me thinks of this almost like a traditional function call.  The embedded template is a function, I pass it some different values, and it returns different results based on those values.  The results, in this case, being a marked up unordered list of titles with a header.  If I want to get a different number of results or link those results to different templates I can just create additional embed variables to use in the embedded template.

The Snippet Approach
Here’s the same idea re-coded using a Snippets-based approach.  With the Snippet I identified what was common about the two lists and placed that code off in a Snippet.  The parent template then houses the first part of the of the channel:entries tag so that I can specify a different channel parameter.

<h1>Test Snippets</h1>
<
p>The following two lists are returned using one snippet for everything common between the two tag pairsThe only thing kept in the parent template is what has to be different just the channel name in this case.</p>

<
h5>Latest Salads</h5>
{exp:channel:entries channel="salads" {snp_list_guts}

<h5>Latest Restaurants</h5>
{exp:channel:entries channel="restaurants" {snp_list_guts} 

Here is the code that’s then centralized into the snp_list_guts Snippet:

limit="5" disable="custom_fields|categories|member_data|pagination" dynamic="no"}

{if count
==1}
    
<ul>
{/if}

<li>{title}</a></li>

{if count==total_results}
    
</ul>
{/if}

{
/exp:channel:entries} 

The amount of code in the Snippets parent template is almost exactly the same as sample Embedded Template parent template.  However - call it force of habit - not seeing the complete channel:entries tag pair in one template bothers me.  Changes to the parameters of the tag would be easy enough to handle (like if I wanted a different limit on one vs the other), but things like building a different link in the middle of the template would be harder to do - I’d have to split the one Snippet in two.

What About Performance?
Regardless of the appeal of the code itself I wanted to see what performance differences there would be between the two approaches. I turned on ExpressionEngine’s Output Profiler and found the following (all running on my local machine on a relatively small EE test site):

Snippets:
Average Total Execution Time (10 page loads): .5414
Memory: 7,549,656 bytes
Queries: 23

Embeds
Average Total Execution Time (10 page loads) .5628
Memory: 7,562,520 bytes
Queries: 25

Compare:
Snippets ran ~ 4% faster.
Snippets used ~1% less memory
Snippets used ~ 8% fewer queries

So?
The Snippet-based approach has obvious performance gains, even on my small & local site.  Those results might be more impressive on a larger site, bigger database, and more complex content.  However I’m still somewhat ambivalent about switching to them.  You still can’t organize Snippets into groups.  You can’t save them as files (at least with native EE functionality, there is now a third party addon that lets you). And I’m still bothered by seeing EE tag pairs split between templates. 

However as a means to improve performance on a site that needs it Snippets would be well-worth investigating.

What about you - have you found a way to use Snippets that you think is pretty cool and want to share?

Category Navigation

<< Previous Entry   

Next Entry >>

 

Previous Comments

Picture of Christopher Kennedy

by Christopher Kennedy

Date: Wednesday, December 1st, 2010
Comment: #1

Great article, Mike. I’ve definitely been dabbling more into Snippets as of late, if only for the bigger prominence and easier client hand-off.

Also, it’s worth noting that as of today, Mountee ( http://hellomountee.com ) now supports access to Snippets and Global Variables, even though it’s just a direct access to the db and not “real” files.

Mike Boyink

by Mike Boyink (Author)

Date: Wednesday, December 1st, 2010
Comment: #2

Good point on Mountee.

You let clients into Snippets?

Picture of Curtis Blackwell

by Curtis Blackwell

Date: Wednesday, December 1st, 2010
Comment: #3

There’s also a free add-on by Bjorn Borresen on devot:ee (DevKit: http://devot-ee.com/add-ons/devkit-for-ee-2.0/) that allows you to save snippets and global variables as files, but it also does some other stuff, so it can be overkill a lot of the time.

Picture of Brian

by Brian

Date: Wednesday, December 1st, 2010
Comment: #4

Mike, I’m going to be releasing an extension soon that syncs snippets from the file system, and it mimics the template folder structure for MSM support. It will also hide the Snippets link in the main menu so clients can’t get to them. There is another add-on out there, I think the dev kit thing that does this too, but my extension will only handle syncing of snippets, nothing more.

I can send you what I have so far… it’s usable, just needs testing.

I’ve also made this request with EllisLab, and has been sent to their devs throught Twitter… if they implement this, Snippets will be much, much more usable. That change, and with my extension I plan on using Snippets as much as possible. http://expressionengine.com/forums/viewthread/174119/

Picture of Brian

by Brian

Date: Wednesday, December 1st, 2010
Comment: #5

Heh, it’s also good to know that I don’t have to have the opening and closing tags in the same location… freaky that you can split it up like that. Thanks for pointing it out.

Picture of Lodewijk Schutte

by Lodewijk Schutte

Date: Wednesday, December 1st, 2010
Comment: #6

The thing to remember with snippets is, that they’re just string replacements in the template, executed before the {exp} tags are parsed. Therefore, they can contain anything, and from the moment they are replaced, are part of the template as if they were there from the beginning.

Let me blatantly promote Low Variables, where you can create snippets (early parsed global variables) and can have more control over what is allowed in them, making it ideal for, say, custom parameter values or other settings.

Picture of Tony Geer

by Tony Geer

Date: Wednesday, December 1st, 2010
Comment: #7

Thanks for the analysis Mike.

Apart from the popular use of having snippets store my disable and date format parameters, I haven’t used them to do anything else as yet.

Picture of John Faulds

by John Faulds

Date: Wednesday, December 1st, 2010
Comment: #8

Where I found snippets handy recently was I had to build a site that had a banner on every page which was populated from a matrix field with a handful of different options. Because it had to appear on a variety of different templates, I wanted to have a single location to edit it.

I could’ve used an embedded template but that would’ve meant passing in quite a few embedded variables.

With a snippet I just cut the channel entries code out of the template, created a snippet out of it and then added the snippet to the templates.

Picture of Luke

by Luke

Date: Thursday, February 24th, 2011
Comment: #9

Am I right in this concept?

I could use snippets to create semantic names to my template groups?

for example a snippet named the_cart_group that contains:

cart

Then in all template when using something like :

{path=’{the_cart_group}’}

This would mean when I could rename the template group proper from ‘cart’ to ‘shoppingcart’ and just update the snippet without having to fix all my template links?

Thanks.

Picture of Luke

by Luke

Date: Thursday, February 24th, 2011
Comment: #10

Confirmed my idea worked.

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...

dy>