Skip to content

Instantly share code, notes, and snippets.

@saevarom
Last active August 29, 2015 14:14
Show Gist options
  • Save saevarom/d09849c47c896c5d9c66 to your computer and use it in GitHub Desktop.
Save saevarom/d09849c47c896c5d9c66 to your computer and use it in GitHub Desktop.
Simple Javascript template rendering using Mustache

Define templates using keys:

Template.register("event-detail",
    '<div class="event-detail">' +
    '  <h2>{{ title }}</h2>' +
    '  <p>{{ description }}</p>' +
    '</div>';
);

Call templates in code:

var context = {title: "This is a title", description: "This is a description"};
$('#event').html(Template.render("event-detail", context));
var _Template, Template;
_Template = (function(){
function Template(){
this.templates = {};
}
Template.prototype.register = function(name, template) {
this.templates[name] = Mustache.compile(template);
};
Template.prototype.get = function(name) {
return this.templates[name];
};
Template.prototype.render = function(name, context) {
return this.templates[name](context);
};
return Template;
})();
var Template = new _Template();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment