Created
September 12, 2018 15:21
-
-
Save mortenege/6a42a58c50335731d63ed19c2357e82b to your computer and use it in GitHub Desktop.
Inject object data into string via templating
This file contains hidden or 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
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