3

I want to do a simple application using backbonejs with mustache template. Can you give me a sample program??

New node file:

var Person = Backbone.Model.extend({
    defaults: {
        name: 'Guest Worker',
    }
});

var PersonView = Backbone.View.extend({
    tagName: 'li',
    initialize: function(){
        _.templateSettings = {
              interpolate: /\{\{(.+?)\}\}/g
            };

        this.render();
    },
    render: function(){
        var template1 = _.template("Hello {{ name }}!");        
        this.$el.html( this.template1(this.model.toJSON()));
    }
});

This is my js code.

guptha
  • 529
  • 1
  • 4
  • 9
Siva Rajamani
  • 59
  • 1
  • 14

2 Answers2

2

Mustache template engine doesn't work this way. Here's a small example from the documentation :

var view = {
    title: "Joe",
    calc: function () {
        return 2 + 4;
    }
};
// output will then contain processed html
var output = Mustache.render("{{title}} spends {{calc}}", view);

Anyway, i would recommend you using Handlebars (http://handlebarsjs.com/) instead of Mustache. It's almost the same syntax (and it has partials as Mustache does), but far more powerful thanks to its helpers.

Finally, you should use something to precompile your templates. You can either use handlebars's one (http://handlebarsjs.com/precompilation.html) or another one like Brunch, or Grunt.

[Edit] OK, let's try to elaborate a bit... I won't give you any complete example (i don't have one right now, and it wouldn't teach you anything), but the one i posted above should be sufficient to understand Mustache basics. Now you have to find a way to precompile your templates, here's an answer with some clues : How to load templates with Hogan.JS from an external file?

Community
  • 1
  • 1
Akaryatrh
  • 532
  • 2
  • 10
2

While an underscore template is set like this in Backbone.js:

template: _.template(...)

A mustache template is set like this:

template: Mustache.render.bind(null,<template>) 
    //Mustache.render(template,view,[partials])
    //a partial function is created because this.template should be a function
    //<function>.bind() creates the partial function

don't do these:

template: Mustache.to_html(<template>) // deprecated
// or
template: Mustache.to_html.bind(null,<template>) // deprecated
// Use Mustache.render() and not Mustache.to_html()
Yomi
  • 351
  • 3
  • 4