Skip to content

Instantly share code, notes, and snippets.

@PeterRao
Created February 21, 2017 03:57
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 PeterRao/fa9720f9121b65c6f162b899b7470b87 to your computer and use it in GitHub Desktop.
Save PeterRao/fa9720f9121b65c6f162b899b7470b87 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Virtual Template Example</title>
</head>
<body>
</body>
<script id="user" type="text/template">
</script>
<script>
var str = '{ xxx"xxx"dddd {} }'
// 用渲染函数构建虚拟模版类
function Parser(str) {
this.index = 0
this.str = str
this.stack = []
}
var pp = Parser.prototype
pp.cur = function() {
return this.str[this.index]
}
pp.next = function() {
return this.str[this.index + 1]
}
pp.start = function() {
var endIndex = this.str.length
var logic = ''
var str = ''
var enterString = false
var enterLogic = false
var blockCount = 0
console.log(endIndex)
do {
var cur = this.cur()
if (!enterString) { //非字任串模式
switch (cur) {
case '"':
case "'":
enterString = cur
if (enterLogic) {
logic += cur
}
this.index++;
break
case '{':
blockCount++
if (enterLogic) {
logic += cur
} else {
enterLogic = true
//不添加界定符{
}
this.index++;
break
case '}':
if (enterLogic) {
blockCount--
if (blockCount === 0) {
//不添加界定符 }
enterLogic = false
} else {
logic += cur
}
}
this.index++;
break
default:
if (enterLogic) {
logic += cur
}
this.index++;
break
}
} else { //字符串模式
if (enterLogic) {
logic += cur
}
if (cur === enterString) { //结束
enterString = false
} else {
str += cur
}
this.index++
}
} while (this.index !== endIndex);
console.log(logic)
console.log(str)
}
var a = new Parser(str)
console.log(a)
a.start()
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment