Skip to content

Instantly share code, notes, and snippets.

@pedrochaves
Created January 31, 2012 10:43
Show Gist options
  • Save pedrochaves/1709844 to your computer and use it in GitHub Desktop.
Save pedrochaves/1709844 to your computer and use it in GitHub Desktop.
Small JavaScript function to create python-like string formatting (without the type of the variable)
var str_tpl = function (str, map) {
var prop;
str = str + '';
for (prop in map) {
if (map.hasOwnProperty(prop)) {
str = str.replace('%(' + prop + ')', map[prop]);
}
}
return str;
}
// Example
var TEMPLATE = '<div id="%(divID)">%(content)</div>';
var html = str_tpl(TEMPLATE, {
"divID": "minha-div",
"content": '<a href="#">Qualquer HTML</a>'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment