Last active
April 25, 2018 19:30
-
-
Save sorenlouv/7034f47583f6ddd21869d148526955a8 to your computer and use it in GitHub Desktop.
Recursively Iterate a nested structure and render strings as mustache templates
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
const input = { | |
email: { | |
subject: 'Happy birthday {{name}} 🎂', | |
body: 'Hi {{name}}, you are turning {{age}} today!' | |
} | |
}; | |
const ctx = { name: 'Søren', age: 30 }; | |
const tmpl = renderMustache(input, ctx); | |
// tmpl: {"email": {"subject": "Happy birthday Søren 🎂", "body": "Hi Søren, you are turning 30 today!"}} |
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
import { isObject, isArray, isString } from 'lodash'; | |
function renderMustache(input, ctx) { | |
if (isString(input)) { | |
return mustache.render(input, ctx); | |
} | |
if (isArray(input)) { | |
return input.map(itemValue => renderMustache(itemValue, ctx)); | |
} | |
if (isObject(input)) { | |
return Object.keys(input).reduce((acc, key) => { | |
const value = input[key]; | |
return { ...acc, [key]: renderMustache(value, ctx) }; | |
}, {}); | |
} | |
return input; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment