Monday, November 4, 2013

Handlebars Templating?

var topics = ['Easy Handlebars Templating'];
topics.shift();
//'Easy Handlebars Templating'
view raw gistfile1.js hosted with ❤ by GitHub

I have been writing small posts lately, so it's probably best if I just cut to the chase.

Handlebars has been tried and true for templating.
Also, I'm in no way advocating for the use of these samples, but I think they speak for themselves. You don't always need a library because you are making an intranet application, or your users use modern browsers. You can code the language yourself!
String.prototype.template = function(templateObject){
return this.replace(/\{\{([a-zA-Z\_0-9\.]*?)\}\}/g, function(match){
var temp = templateObject;
match.slice(2,-2).split('.').forEach(function(item){
temp = temp[item];
});
return temp;
});
};
view raw gistfile1.js hosted with ❤ by GitHub

And one for objects...
Object.prototype.template = function(templateStr){
var that = this;
return templateStr.replace(/\{\{([a-zA-Z\_0-9\.]*?)\}\}/g, function(match){
match.slice(2,-2).split('.').forEach(function(item){
that = that[item];
});
return that;
});
};
view raw gistfile1.js hosted with ❤ by GitHub

"But Josh! I don't want to edit the prototype!"
Fine! Here you go.
function HandleBar(templateStr, templateObject){
var that = templateObject;
return templateStr.replace(/\{\{([a-zA-Z\_0-9\.]*?)\}\}/g, function(match){
match.slice(2,-2).split('.').forEach(function(item){
that = that[item];
});
return that;
});
};
view raw gistfile1.js hosted with ❤ by GitHub

I encourage you to at least understand what is going on in this code before you steal it, and certainly be able to implement it yourself.

No comments:

Post a Comment