Last active
March 2, 2017 05:24
-
-
Save jiahut/9bd979bf0c5a18886ae0d772b5540181 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 compile(template){ | |
var evalExpr = /<%=(.+?)%>/g; | |
var expr = /<%([\s\S]+?)%>/g; | |
template = template | |
.replace(evalExpr, '`);\n echo( $1 );\n echo(`') | |
.replace(expr, '`);\n $1 \n echo(`'); | |
template = 'echo(` ' + template + '`);'; | |
var script = ` | |
(function parse(data){ | |
var output = ""; | |
function echo(html){ | |
output += html; | |
} | |
${ template } | |
return output; | |
})`; | |
return script; | |
} | |
function tokenize(TOKEN_REGEX, str) { | |
let result = []; | |
let match; | |
while(match = TOKEN_REGEX.exec(str)){ | |
result.push(match[1]); | |
} | |
return result; | |
} | |
module.exports = { compile, tokenize }; |
This file contains hidden or 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
node> const { compile } = require('./tpl'); | |
node> var template = ` | |
<ul> | |
<% for(var i=0; i < data.supplies.length; i++) { %> | |
<li><%= data.supplies[i] %></li> | |
<% } %> | |
</ul> | |
`; | |
node> var parse = eval(compile(template)); | |
node> let data = { supplies: ['apple', 'banana', 'orange']}; | |
node> parse(data) | |
node> const { tokenize } = require('./tpl'); | |
node> const Y_TOKEN = /\s*(\+|\-|\*|\/|[0-9])+\s*/y; | |
node> tokenize(Y_TOKEN," 2 + 3 - 4 * 5 / 8 " ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment