Skip to content

Instantly share code, notes, and snippets.

@BlaM
Last active April 10, 2018 11:50
Show Gist options
  • Save BlaM/3fb90d31233a4739dc7d5419839dcdfd to your computer and use it in GitHub Desktop.
Save BlaM/3fb90d31233a4739dc7d5419839dcdfd to your computer and use it in GitHub Desktop.
Micro Mustache JavaScript Function
function Mustache(template, placeholders) {
function isDef(x) { return typeof placeholders[key] === 'undefined'; }
var __tmpElement = document.createElement('span');
function htmlencode(x) { __tmpElement.innerText = x; return __tmpElement.innerHTML; }
function getValue(key) {
var obj = placeholders, keys;
try {
keys = key.split('.');
for (var i = 0; i < keys.length; i++) {
obj = obj[keys[i]];
}
} catch(e) {
obj = '';
}
return String(typeof obj !== 'undefined'? obj : '');
}
return template.replace(/\{\{\s*([a-z0-9_\.-]+)\s*\}\}/g, function(match, key) {
return htmlencode(getValue(key));
}).replace(/\{\{\{\s*([a-z0-9_\.-]+)\s*\}\}\}/g, function(match, key) {
return getValue(key);
});
}

As basic as it gets.

Supports nested attributes.

Mustache('Hallo {{example.test}} foofoo', {example: {test: 'hallo'}});
  • {{foo}} will be HTML-Encoded
  • {{{foo}}} will be "raw"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment