8

Django Handlebars.js integration

 3 years ago
source link: https://blog.mathieu-leplatre.info/django-handlebarsjs-integration.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Django Handlebars.js integration

Django Handlebars.js integration

Sat 17 March 2012

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.

#django, #javascript, #handlebars - Posted in the Dev category


© Copyright 2020 by Mathieu Leplatre. mnmlist Theme

Content licensed under the Creative Commons attribution-noncommercial-sharealike License.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK