Last active
August 29, 2015 14:15
-
-
Save coverslide/96ab4a64ad8b4b0150dc to your computer and use it in GitHub Desktop.
Some simple javascript template functions
This file contains 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
// 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); | |
}); | |
}; | |
} |
This file contains 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
// 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] || ''; | |
}); | |
}; | |
} |
This file contains 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
// 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); | |
}); | |
}; | |
} |
This file contains 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
// 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