BernaMariano
BernaMariano

Reputation: 866

Can Javascript compile Django's template?

I have a template rendered by Django, filled with the context I passed in the view. But I'll need to recompile this template by client-side, with a new context.

After some research I finally came across MustacheJs, but the leak of information brought me some doubts.

Do I have to write only one template.mustache, and both Javascript and Django will be able to compile it?

It seems that Mustache syntax use some symbols like:

{{#items}} {{/items}}

while Django is

{% for item in items %}

They look pretty dissimilar for me... Actually I don't even know if Mustache is what I need, is it possible to do what I want?


Edit

Ok so, let me explain exactly what I need. I have this template:

items.html:

<form action="item/add/">
    <input type="text" class="item-name" name="name">
    <input type="submit" value="New Item">
</form>
{% if items %}
    <ul class="item-list">
    {% for item in items %}
       <li>
           {{ item.name }}
       </li>
    {% endfor %}
    </ul>
{% endif %}

This template is compiled by this view:

def items(request):
    items = Item.objects.all()
    context = {
        'items': items
    }
    return render_to_template('items.html', context)

So this template is compiled and rendered by the server-side. Now let's say the user clicked the added a new item, and this function ran:

addItem: function addItem() {
    var action = this.$form.attr('action');
    $.post(action, {
        name: this.$itemName.val()
    }, function(response) {
        if (response.success) {
            // LOAD FROM THE SAME TEMPLATE DJANGO DID
            var newItem = loadTemplate('items.html', {
                item: response.item
            });
            this.$itemList.append(newItem);
        }
    });
}

What I need is this loadTemplate parser lib, I don't if this exists, but it does, that's what I want!

Upvotes: 1

Views: 296

Answers (1)

arocks
arocks

Reputation: 2882

It is better to use either the Django templating or Mustache templating in a single file. Solutions like django-jstemplate help a great deal in supporting both. There will be a collision of meanings when you use {{ variable }} since both Django and Mustache will try to interpret it. Just be aware of that.

Another simpler option would be to include the Mustache templates inside verbatim blocks. Django templates would not process such blocks.

Upvotes: 1

Related Questions