# jst
**Repository Path**: nutz/jst
## Basic Information
- **Project Name**: jst
- **Description**: 基于JDK8+的nashorn的模板引擎
- **Primary Language**: Java
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: https://nutz.cn
- **GVP Project**: No
## Statistics
- **Stars**: 24
- **Forks**: 1
- **Created**: 2018-06-11
- **Last Updated**: 2022-10-14
## Categories & Tags
**Categories**: template-engine
**Tags**: None
## README
# jst
## 项目介绍
基于JDK8+的nashorn js引擎的模板引擎
[变更历史](ChangeLog.md)
## 使用简介
模板文件
```
# // 逻辑判断,支持所有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}
# }
```
渲染之
```java
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", "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: :5:11 Expected ; but found _
user.name _ "I am ABC";
^ in 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时报错