如何在html中写js,如何在js中优雅地写HTML模板

注释形式写在js中,然后用Function.prototype.toString方法拿到。

var compile = function (functionObject) {

return functionObject.toString().match(/\/\*([\s\S]*?)\*\//)[1];

};

var html = compile(function () {/*

title

content

*/

});

作为模板,当然还需要关键词的替换功能。接下来实现它!

参考ES6中的template string:

`

${title}

${content}

`

只需要替换符合/\$\{\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 () {/*

${title}

${content}

*/

});

var test2 = {

title: 'title string 2',

content: 'content string 2'

};

document.body.innerHTML += toHtml1(test2);

那么如果变量是这样的呢

${data.title}

只需要用.分割字符串,然后逐步拿到值就行了:

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 () {/*

${data.title}

${data.content}

*/

});

toHtml3(test3);

"

title string 3

content string 3

"

See example here.

另:已经有人造了轮子:multiline

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值