Created
September 10, 2012 22:05
-
-
Save wafflesnatcha/3694312 to your computer and use it in GitHub Desktop.
JavaScript: String._template()
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
/** | |
* 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