Skip to content

Instantly share code, notes, and snippets.

@KrofDrakula
Created June 5, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KrofDrakula/57c4f6ee920341325e67 to your computer and use it in GitHub Desktop.
Save KrofDrakula/57c4f6ee920341325e67 to your computer and use it in GitHub Desktop.
Small templating function
// Use `<% ... %>` to execute blocks of JavaScript, `<%= ... %>` to write
// out the result of the embedded expression.
function tmpl(str, params) {
if (!str) return '';
function generateOutput(str) {
return " p.push('" + str.replace(/'/g, "\\'").split(/\r?\n/g).join("\\n');\n p.push('") + "');\n";
}
var fn;
if (str.indexOf('<%') == -1) {
fn = function() { return str; };
} else {
var fragments = str.split(/<%\s*|\s*%>/g),
body = 'var p = []; with(o) {\n',
insideExpression = false;
fragments.forEach(function(frag) {
if (insideExpression) {
if (frag[0] == '=') {
// it's an expression, so output its value
body += " p.push(" + frag.replace(/^=\s*|\s*$/g, '') + ");\n";
} else {
// it's a JavaScript statement
body += " " + frag + '\n';
}
} else if (frag) {
// literal string, just escape
body += generateOutput(frag);
}
insideExpression = !insideExpression;
});
body += '} return p.join("");';
try {
fn = new Function('o', body);
} catch(ex) {
var err = new Error('Cannot parse template! (see `template` property)');
err.template = body;
throw err;
}
}
return params ? fn(params) : fn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment