Emulating Django blocks with Smarty capture

2 January 2010

Django blocks considered addictive

I do Django development for Red Robot Studios and one of the many great things about the Django web framework is the template system.

Using blocks and inheritance, repetitive html is kept to a minimum. For example you can do:

base.html

...
<title>{% block title %}Default Title{% endblock %}</title>
...
<div id="content">
{% block content %}{% endblock %}
</div>
...

home.html

{% extends 'base.html' %}{% block title %}Home Page Title{% endblock %}
{% block content %}
Home page content here
{% endblock %}

The content of the blocks in home.html are plugged in to the block placeholders in base.html.

Smarty doesn’t have blocks like Django

Update: Wait a minute. I’m wrong. Smarty does have blocks, as Richard pointed out in the comments. Uh, how did I miss that?

Smarty is a template system for php. I was using it recently for a client and wished I could use Django-style blocks. Smarty doesn’t have blocks and inheritance, but does have capture and include. Here’s how I was able to achieve a similar result.

Using Smarty capture to emulate blocks

Using Smarty’s capture and include functions, here’s how the templates look:

header.tpl

...
<title>{if $smarty.capture.title}{$smarty.capture.title}{else}Default Title{/if}</title>
...
<div id="content">
{$smarty.capture.content}
</div>
...

home.tpl

{capture name='title'}Home Page Title{/capture}
{capture name='content'}
Home page content here
{/capture}

{include file='header.tpl'}

Simple, no? Remember to do these captures before including the file.

It’s not as powerful as Django template inheritance, but it’s a reasonable attempt to use Django-style blocks in Smarty templates.

Filed under: Web Development — Scott @ 12:34 am