Fork me on GitHub

Django Handlebars.js integration

In order to write Handlebars.js templates in Django templates, I was gonna copy and paste for the second time Miguel Araujo's verbatim snippet. But since one of the Django weakness is the lack of reusable applications, I thought I would package one instead :)

The two existing django applications [1] that integrate Handlebars.js are somehow bloated, they both kind of compile or render javascript templates on server-side (sic).

Oppositely, my django-templatetag-handlebars is very simple, you write your Handlebars template inside your django template. Django will preserve nicely {} tags, but still render {% %} tags.

For example, with this in your template :

{% tplhandlebars "tpl-infos" %}
    {{total}} {% trans "result(s)." %}
    <p>{% trans "Min" %}: {{min}}</p>
    <p>{% trans "Max" %}: {{max}}</p>
{% endtplhandlebars %}

The following block with end-up in your page :

<script id="tpl-infos" type="text/x-handlebars-template">
    {{total}} result(s).
    <p>Min: {{min}}</p>
    <p>Max: {{max}}</p>
<script>

Render it, client-side, as usual using Handlebars API :

var properties = {
    total: 10,
    min: 4,
    max: 5
};

var template = Handlebars.compile($('#tpl-infos').html()),
    rendered = template(properties);

Your rendered string is ready, and waiting to be inserted in your DOM :)

10 result(s).
<p>Min: 4</p>
<p>Max: 5</p>

Download and more info.

[1]Both named django-handlebars, by Sergii Iavorskyi and by Chris Vigelius.

Comments !

social