Skip to content

Instantly share code, notes, and snippets.

@gryzzly
Created November 14, 2011 17:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gryzzly/1364474 to your computer and use it in GitHub Desktop.
Save gryzzly/1364474 to your computer and use it in GitHub Desktop.
renderTemplate from DoAT Touchy, basic JS templating
// Render JavaScript template (from http://git.io/B7KxZg DoAT Touchy)
//
// You can place your template in a script tag with type other than "text/javascript"
// such as "text/html", like this:
// <script type="text/html" id="item-template">
// <li id="{{id}}">
// <p>{{content}}</p>
// </li>
// You'd then render your template like this:
// var itemTemplate = document.getElementById('item-template').innerHTML;
// renderTemplate( itemTemplate, {
// id : "item1",
// content : "lorem ipsum dolor sit amet …"
// });
var renderTemplate = function(str, attrArr){
if (!attrArr){return str}
for (var key in attrArr){
var keyRegex = new RegExp("{"+key+"}", "g");
var value = attrArr[key];
str = str.replace(keyRegex, value);
}
return str;
};
@gryzzly
Copy link
Author

gryzzly commented Jun 29, 2012

var renderTemplate = function(tpl, dict) {
    if (!dict) return tpl;
    return tpl.replace(/\{([\w.\-]+)\}/g, function(key, submatch) {
        return ({}).hasOwnProperty.call(dict, submatch) ? dict[submatch] : key;
    });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment