8 Star 25 Fork 1

Nutz / jst

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 2.14 KB
一键复制 编辑 原始数据 按行查看 历史

jst

项目介绍

基于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时报错

Java
1
https://gitee.com/nutz/jst.git
git@gitee.com:nutz/jst.git
nutz
jst
jst
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891