Enjoy Template Engine一如既往地坚持极简设计,核心只有 #if、#for、#switch、#set、#include、#define、#(…) 这七个指令,便实现了传统模板引擎几乎所有的功能。如果官方提供的指令无法满足需求,还可以极其简单地在模板语言的层面对指令进行扩展。
public class DemoConfig extends JFinalConfig {
public void configConstant(Constants me) {}
public void configRoute(Routes me) {}
public void configEngine(Engine me) {
//自定义指令国家选择框
me.addDirective("countrySelect", CountryDirective.class);
}
public void configPlugin(Plugins me) {}
public void configInterceptor(Interceptors me) {}
public void configHandler(Handlers me) {}
}
自定义指令示例:
package com.flmall.system.directive;
import java.io.IOException;
import com.flmall.base.service.UserService;
import com.flmall.common.model.SystemUser;
import com.flmall.system.service.LoginService;
import com.jfinal.aop.Aop;
import com.jfinal.kit.Kv;
import com.jfinal.render.RenderManager;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
/****
* #countrySelect("id","name","class","countryCode");
*
*/
public class CountryDirective extends Directive{
private Expr id;
private Expr name;
private Expr className;
private Expr countryCode;
@Override
public void setExprList(ExprList exprList) {
int paraNum = exprList.length();
if (paraNum != 4) {
throw new ParseException("The parameter of #number directive can not be blank", location);
}
id = exprList.getExpr(0);
name = exprList.getExpr(1);
className = exprList.getExpr(2);
countryCode = exprList.getExpr(3);
}
@Override
public void exec(Env env, Scope scope, Writer writer) {
SystemUser account = (SystemUser)scope.getRootData().get(LoginService.loginAccountCacheName);
UserService userService = Aop.get(UserService.class);
Kv kv = Kv.by("id", id.eval(scope)).set("name", name.eval(scope))
.set("className", className.eval(scope))
.set("countryCode", countryCode.eval(scope))
.set("countryList", userService.getCountryList(account.getId()));
String content = RenderManager.me().getEngine().getTemplate("_views/directive/country_directive.html").renderToString(kv);
try {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
指令country_directive.html示例:
<select id="#(id??)" name="#(name??)" class="#(className??)">
<option value="">请选择</option>
#for(x : countryList)
<option value="#(x.countryCode)" #if(countryCode&&x.countryCode==countryCode) selected="selected" #end>#(x.countryName)</option>
#end
</select>
页面使用示例:
td> 国家: </td>
<td>#countrySelect("countryCode","countryCode","form-control","")</td>