代码拉取完成,页面将自动刷新
基于JDK8+的nashorn js引擎的模板引擎
模板文件
# // 逻辑判断,支持所有js语法
# if (age > 10) {
${age} > 10
# }
# // 遍历int数组
# for (var i in ids) {
ids[${i}] = ${ids[i]}
# }
# // 遍历对象数组
# for (var i in users) {
users[${i}].age = ${users[i].age}
users[${i}].name = ${=users[i].name}
# }
<!--#
// 这是多行js语句片段的开头
// 这是多行js语句片段的结尾
#-->
渲染之
Context ctx = Lang.context();
// 简单遍历
ctx.set("age", 30);
// 数组
ctx.set("ids", new int[]{30, 40, 50, 60});
// 对象数组,注意有注入
ctx.set("users", Arrays.asList(
new NutMap("name", "<script>alert('hahaha')</script>wendal").setv("age", 30),
new NutMap("name", "zozoh").setv("age", 40),
new NutMap("name", "pangwu").setv("age", 30)
));
JstImpl tmpl = Jst.createFromFile("simple.jst");
tmpl.compile();
String re = tmpl.render(ctx);
#
开头的是单行js语句段<!--#
和 #-->
多行js语句段的开头和结尾${}
是js表达式占位符, 如需抹除html特殊字符,加个等号就可以了, ${=xxx}
典型的错误提示会包含行数和错误信息
org.nutz.jst.JstException: <eval>:5:11 Expected ; but found _
user.name _ "I am ABC";
^ in <eval> at line number 5 at column number 11
3 : ${user.location.city}
4 : # 下一行会语法错误
5 > # user.name _ "I am ABC";
6 : # user.location = {}
第5行的下划线应该是等号,属于js语法错误
org.nutz.jst.JstException: TypeError: Cannot read property "city" from undefined in org/nutz/jst/test/tmpls/with_error.jst at line number 3
1 : # var user = {};
2 : # user.loc = {};
3 > ${user.location.city}
4 : # user.name = "I am ABC";
5 : # user.location = {}
第三行的user.location为null,所以读取city时报错
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。