Skip to content

Instantly share code, notes, and snippets.

@datfaf
Forked from couchoud/supplant.js
Created March 14, 2012 12:41
Show Gist options
  • Save datfaf/2036211 to your computer and use it in GitHub Desktop.
Save datfaf/2036211 to your computer and use it in GitHub Desktop.
basic hs templating using String object and Regex
if (typeof String.prototype.supplant !== 'function') {
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' ? r : a;
});
};
}
/**
usage:
mydiv.innerHTML = template.supplant(data);
var template = '<table border="{border}">' +
'<tr><th>Last</th><td>{last}</td></tr>' +
'<tr><th>First</th><td>{first}</td></tr>' +
'</table>';
var data = {
first: "Carl",
last: "Hollywood",
border: 2
};
*/
// variations
var reSupplant = /{([^{}]*)}/g;
function supplant( string, obj ) {
return string.replace(reSupplant,
function (a, b) {
var r = obj[b];
return typeof r === 'string' ? r : a;
});
}
function trim(stuff) {
if (''.trim)
return stuff.trim();
else
return s.replace(/^\s+/, '').replace(/\s+$/, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment