Created
June 5, 2015 16:59
-
-
Save KrofDrakula/57c4f6ee920341325e67 to your computer and use it in GitHub Desktop.
Small templating function
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
// 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