Skip to content

Instantly share code, notes, and snippets.

@coverslide
Last active August 29, 2015 14:15
Show Gist options
  • Save coverslide/96ab4a64ad8b4b0150dc to your computer and use it in GitHub Desktop.
Save coverslide/96ab4a64ad8b4b0150dc to your computer and use it in GitHub Desktop.
Some simple javascript template functions
// all falsy values do not display
function makeTemplate (html) {
return function (data) {
return html.replace(/\{\{\s*([^\s}]+?)\s*\}\}/g, function (match, key) {
return key.split('.').reduce(function (data, key) {
return data ? (data[key] || '') : '';
}, data);
});
};
}
// very simple, no object traversal, skips falsy values
function makeTemplate (html) {
return function (data) {
return html.replace(/\{\{\s*([^\s}]+?)\s*\}\}/g, function (match, key) {
return data[key] || '';
});
};
}
// allows for false and 0 to be displayed
function makeTemplate (html) {
return function (data) {
return html.replace(/\{\{\s*([^\s}]+?)\s*\}\}/g, function (match, key) {
return key.split('.').reduce(function (data, key) {
if (typeof data != 'object') {
return data;
}
var value = data[key];
if (typeof value == 'number' || typeof value == 'boolean') {
return value;
}
return value || '';
}, data);
});
};
}
// allows for just 0 to be displayed
function makeTemplate (html) {
return function (data) {
return html.replace(/\{\{\s*([^\s}]+?)\s*\}\}/g, function (match, key) {
return key.split('.').reduce(function (data, key) {
if (typeof data != 'object') {
return data;
}
return (data[key] === 0 && '0') || data[key] || '';
}, data);
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment