注釋形式寫在js中,然后用Function.prototype.toString方法拿到。
var compile = function (functionObject) {
return functionObject.toString().match(/\/\*([\s\S]*?)\*\//)[1];
};
var html = compile(function () {/*
<div>
<h2>title</h2>
<div class="content">content</div>
</div>
*/
});
作為模板,當然還需要關鍵詞的替換功能。接下來實現它!
參考ES6中的template string:
`
<div>
<h2>${title}</h2>
<div class="content">${content}</div>
</div>
`
只需要替換符合/\$\{\w.+\}/g
這個正則的文本即可。
用replace方法:
.replace(/\$\{\w.+\}/g, function (variable) {
return otherValue;
});
去掉${
和}
,然后返回實際值即可。
var compile = function (functionObject) {
return function (it) {
return functionObject.toString().match(/\/\*([\s\S]*?)\*\//)[1].replace(/\$\{\w.+\}/g, function (variable) {
return it[variable];
});
}
};
測試下:
var toHtml1 = compile(function () {/*
<div>
<h2>${title}</h2>
<div class="content">${content}</div>
</div>
*/
});
var test2 = {
title: 'title string 2',
content: 'content string 2'
};
document.body.innerHTML += toHtml1(test2);
那么如果變量是這樣的呢<h2>${data.title}</h2>
?
只需要用.
分割字符串,然后逐步拿到值就行了:
var value = it;
variable = variable.replace('${', '').replace('}', '');
variable.split('.').forEach(function (section) {
value = value[section];
});
return value;
測試下:
var test3 = {
data: {
title: 'title string 3',
content: 'content string 3'
}
};
var toHtml3 = compile(function () {/*
<div>
<h2>${data.title}</h2>
<div class="content">${data.content}</div>
</div>
*/
});
toHtml3(test3);
"
<div>
<h2>title string 3</h2>
<div class="content">content string 3</div>
</div>
"
See example here.
另:已經有人造了輪子:multiline