Skip to content

Instantly share code, notes, and snippets.

@mortenege
Created September 12, 2018 15:21
Show Gist options
  • Save mortenege/6a42a58c50335731d63ed19c2357e82b to your computer and use it in GitHub Desktop.
Save mortenege/6a42a58c50335731d63ed19c2357e82b to your computer and use it in GitHub Desktop.
Inject object data into string via templating
var fillTemplate = function (str, obj) {
var regex = /{{ *(\w+) *}}/g;
return str.replace(regex, function(lit, key){
if (!obj.hasOwnProperty(key)) return lit;
return obj[key];
})
}
// Example usage
var str = "<div><h1>{{ post_title }}</h1><small>{{ author }}</small><div>{{ content }}</div></div>";
var obj = {post_title: 'Hello, World', author: 'Morten Ege', content: 'This is a quick example of templates'};
var newStr = fillTemplate(str, obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment