This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var topics = ['Easy Handlebars Templating']; | |
topics.shift(); | |
//'Easy Handlebars Templating' |
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
}; |
And one for objects...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
}; |
"But Josh! I don't want to edit the prototype!"
Fine! Here you go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
}; |
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