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:


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


{% 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:


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


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

{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

1 Comment »

  1. Smarty does indeed have blocks.


    Comment by Richard — 16 May 2011 @ 5:28 pm

RSS feed for comments on this post.

Leave a comment