Created
July 10, 2013 13:52
-
-
Save muratpurc/5966454 to your computer and use it in GitHub Desktop.
JS: Simple JavaScript templating
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
/** | |
* Simple templating, replaces occurrence of replacements in passed template | |
* against the values in passed replacements, where the key of replacements will be | |
* mapped to the items to be replaced. | |
* | |
* Usage: | |
* <code><pre> | |
* var template = '<a href="{url}" title="{title}">{text}</a>'; | |
* var replacements = { | |
* url: 'http://www.google.com', | |
* title: 'Visit Google', | |
* text: 'www.google.com' | |
* }; | |
* var result = renderTemplate(template, replacements); | |
* </pre></code> | |
* | |
* @param {String} template The template string with replacements | |
* @param {Object} replacements Object containing replacement values. | |
* @return {String} The rendered template | |
*/ | |
function renderTemplate(template, replacements) { | |
if (!replacements || typeof replacements !== 'object') { | |
return template; | |
} | |
var name; | |
for (name in replacements) { | |
if (replacements.hasOwnProperty(name)) { | |
template = template.replace(new RegExp('{' + name + '}', 'g'), replacements[name]); | |
} | |
} | |
return template; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment