springboot 环境
查询字典标签
@Component public class DicTag implements TemplateDirectiveModel { @Autowired private IDicService dicService; @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { //字典类型 String TYPE = "type" ; //字典父id String PID = "pid" ; String type; Integer pid; if (params.containsKey(TYPE)){ type = params.get(TYPE).toString(); } else { throw new KrtException( "字典类型不能为空" ); } if (params.containsKey(PID)){ pid = Integer.valueOf(params.get(PID).toString()); } else { pid = SysConstant.DEFAULT_PID; } List<Dic> dicList = dicService.selectByTypeAndPid(type,pid); loopVars[ 0 ] = new SimpleSequence(dicList,env.getObjectWrapper()); body.render(env.getOut()); } } |
实现TemplateDirectiveModel 接口
重写execute方法参数说明 这里可以做数据库查询 ,或者渲染模板数据输出
env 当编写复杂的标签时需要使用 一般用不到
params标签输入参数
loopVars 标签输出参数
body 标签体
SimpleSequence 是freemarker的数据类型 freemarker不能直接使用java的数据类型
以上代码编写完成后 设置全局变量时标签生效
@Component public class FreemarkerConfig implements InitializingBean { @Autowired private Configuration configuration; @Autowired private DicTag dicTag; @Override public void afterPropertiesSet() throws Exception { // shiro标签 configuration.setSharedVariable( "shiro" , new ShiroTags()); //标签名与标签类 configuration.setSharedVariable( "dic" , dicTag); } } |
模板上使用标签
<@dic type="region_type";typeList> <#list typeList as type> < option value = "${type.code}" >${type.name}</ option > </#list> </@dic> |
type 是输入参数 字典type 多个参数中间空格 多个输出参数 用“,”隔开 typeList 就是字典数据
官方文档http://freemarker.foofun.cn/pgui_datamodel_directive.html