Skip to content

Instantly share code, notes, and snippets.

@wafflesnatcha
Created September 10, 2012 22:05
Show Gist options
  • Save wafflesnatcha/3694312 to your computer and use it in GitHub Desktop.
Save wafflesnatcha/3694312 to your computer and use it in GitHub Desktop.
JavaScript: String._template()
/**
* Create a string from a template.
*
* Returns a new string with all "<%variables%>" replaced with their corresponding
* properties from the given object argument.
*
* Example:
* <code>
* var data = {
* name: 'Scott',
* description: 'Ante fermentum interdum porttitor rhoncus sem velit, aenean mus nulla porta volutpat.'
* };
* var str = '<div><b><%name%></b><p><%description%></p><%will be removed%></div>'
* console.log(str.template(data));
* </code>
*
* @param {Object} data The object containing replacement data for the template variables.
* @returns {String}
* @author Scott Buchanan <[email protected]>
* @link http://wafflesnatcha.github.com
*/
String.prototype._template = function (data) {
var prop, result = this;
data = data || {};
for (prop in data) {
if (data.hasOwnProperty(prop)) {
result = result.replace('<%' + prop + '%>', data[prop]);
}
}
return result.replace(/<%.+?%>/ig, '');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment