Skip to content

Instantly share code, notes, and snippets.

@sqren sqren/demo.js
Last active Apr 25, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.