Skip to content

Instantly share code, notes, and snippets.

@muratpurc
Created July 10, 2013 13:52
Show Gist options
  • Save muratpurc/5966454 to your computer and use it in GitHub Desktop.
Save muratpurc/5966454 to your computer and use it in GitHub Desktop.
JS: Simple JavaScript templating
/**
* 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