Skip to content

Instantly share code, notes, and snippets.

@couchoud
Created September 11, 2009 15:01
Show Gist options
  • Save couchoud/185339 to your computer and use it in GitHub Desktop.
Save couchoud/185339 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