Created
September 14, 2011 19:24
-
-
Save spocke/1217517 to your computer and use it in GitHub Desktop.
Small and fast template engine
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
(function(namespace) { | |
function template(template) { | |
var index = 0, depth = 0, source = "var o = '', e = encode;", matches, token, value, tokenRe = /{(\/)?(if|each|\$+|%+)\s*(?:([^}]+)|)?\}/g; | |
template = template.replace(/'/g, "\\'"); | |
while (matches = tokenRe.exec(template)) { | |
if (index < matches.index) { | |
source += "o += '" + template.substr(index, matches.index - index) + "';"; | |
} | |
index = matches.index + matches[0].length; | |
token = matches[2]; | |
value = matches[3]; | |
if (token === '$') { | |
source += "o += e(d." + value + ");"; | |
} else if (token === '$$') { | |
source += "o += d." + value + ";"; | |
} else if (matches[1]) { | |
source += '} '; | |
if (token === 'each') { | |
depth--; | |
} | |
} else if (token === 'each') { | |
value = value.replace(/\$/g, 'd.').replace(/%/g, ''); | |
source += ( | |
'for (var index% = 0, length% = ' + value + '.length, value%; index% < length%; index%++) {' + | |
'value% = ' + value + '[index%];' | |
).replace(/%/g, depth ? depth : ''); | |
depth++; | |
} else if (token === 'if') { | |
source += 'if (' + value.replace(/\$/g, 'd.') + ') {'; | |
} else if (token === '%') { | |
source += "o += e(" + value + ");"; | |
} else if (token === '%%') { | |
source += "o += " + value + ";"; | |
} | |
} | |
if (index < template.length) { | |
source += "o += '" + template.substr(index) + "';"; | |
} | |
source += "return o;"; | |
return new Function("d", "encode", source); | |
}; | |
namespace.template = function(tpl) { | |
var rawCharsRegExp = /[<>&\"\']/g, baseEntities = { | |
'\"' : '"', // Needs to be escaped since the YUI compressor would otherwise break the code | |
"'" : ''', | |
'<' : '<', | |
'>' : '>', | |
'&' : '&' | |
}; | |
function encode(text) { | |
return ('' + text).replace(rawCharsRegExp, function(chr) { | |
return baseEntities[chr] || chr; | |
}); | |
}; | |
tpl = template(tpl); | |
return function(data) { | |
return tpl(data, encode); | |
}; | |
}; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment