Skip to content

Instantly share code, notes, and snippets.

@sorenlouv
Last active April 25, 2018 19:30
Show Gist options
  • Save sorenlouv/7034f47583f6ddd21869d148526955a8 to your computer and use it in GitHub Desktop.
Save sorenlouv/7034f47583f6ddd21869d148526955a8 to your computer and use it in GitHub Desktop.
Recursively Iterate a nested structure and render strings as mustache templates
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!"}}
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