Skip to content

Instantly share code, notes, and snippets.

@pentaphobe
Last active August 8, 2016 07:14
Show Gist options
  • Save pentaphobe/7955994 to your computer and use it in GitHub Desktop.
Save pentaphobe/7955994 to your computer and use it in GitHub Desktop.
Rapid-stache
/**
* This doesn't pretend to be a proper, or fully-featured templating library
* it's merely a light-weight one used for rapid prototyping.
* Anti-Features:
* - no precompilation
* - no fancy iteration or repeats
* - pretty much nothing except string replacement
* - basic filters
*
* https://gist.github.com/pentaphobe/7955994
**/
!function InitialiseLibrary (window) {
var __ = window.__ || ( window.__ = {} );
__.template = function(txt, defaults) {
var _open = '{{';
var _close = '}}';
return function splitter(obj) {
var idx = 0;
var len = txt.length;
var result = '';
obj = __.extend({}, defaults, obj);
function resetProto() {
obj.prototype = oldProto;
}
while (idx < len) {
var openIdx = txt.indexOf(_open, idx);
if (openIdx === -1) {
break;
}
result += txt.substring(idx, openIdx);
var closeIdx = txt.indexOf(_close, openIdx+2);
if (closeIdx === -1) {
console.error('Unclosed template data - got as far as:', result);
return false;
}
var key = txt.substring(openIdx+2, closeIdx);
// assume the first char is '=' for now
var cmd = key.charAt(0);
key = key.substring(1);
// parse filter pipes
var filters = key.split('|').map( function(txt) { return txt.trim(); } )
key = filters[0];
filters = filters.slice(1);
var tempResult = obj[key];
filters.forEach( function(item, idx) {
tempResult = __.filter(item, tempResult);
});
result += tempResult;
idx = closeIdx + 2;
}
if (idx < len) {
result += txt.substring(idx);
}
return result;
};
};
__.extend = function() {
if (!arguments.length) return false;
var obj = arguments[0];
for (var i=1, max=arguments.length ; i < max; i++) {
var arg = arguments[i];
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
obj[key] = arg[key];
}
}
}
return obj;
};
__.filters = {
toUpperCase : function(txt) { return txt.toUpperCase(); },
toLowerCase : function(txt) { return txt.toLowerCase(); }
};
/**
* Performs a named filter on the supplied data
*/
__.filter = function(name, data) {
if (!__.filters[name]) return data;
return __.filters[name](data);
};
}(this);
/**
* Basic usage example extracted from the original gist
*/
!function main() {
tpl = 'hello {{=name}}, I am a {{=adjective | toUpperCase}} templating system';
go = __.template(tpl, {name:'nobody', adjective:'poorly-utilised'});
console.log(go());
console.log(go({
name:'john',
adjective: 'doughy'
}));
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment