Created
September 11, 2009 15:01
-
-
Save couchoud/185339 to your computer and use it in GitHub Desktop.
basic hs templating using String object and Regex
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
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