博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Freemarker自定义指令
阅读量:2493 次
发布时间:2019-05-11

本文共 2757 字,大约阅读时间需要 9 分钟。

场景

在做一个CMS网站时,要列出网站栏目,比如有新闻,科技,体育,财经等栏目。栏目内容存放在数据库中。

调用语法

//没有循环变量        <@user_def_dir_exp param1=val1 param2=val2 ... paramN=valN/>                //有循环变量        <@user_def_dir_exp param1=val1 param2=val2 ... paramN=valN ;lv1, lv2, ..., lvN/>

自定义指令使用

cms_chanel_list指令的作用是按传入的参数count找出指定数量的栏目,并且过滤掉名字为“体育”的栏目。

<@cms_chanel_list count=5 exclude="体育">        <#list chllist as c>        
${c.name}

自定定义指令

首先要实现TemplateDirectiveModel接口。

public class ChanelListDirective implements TemplateDirectiveModel {    @Inject    private ChanelDao chanelDao;    /*     * @param 传入的参数,params类型为Map
,由于历史原因没用泛型。比如传入参数“count=5”,String为count,TemplateModel为5 * * @loopVars 循环变量 * * @see freemarker.template.TemplateDirectiveModel#execute(freemarker.core. * Environment, java.util.Map, freemarker.template.TemplateModel[], * freemarker.template.TemplateDirectiveBody) */ public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { // TODO Auto-generated method stub if (params == null || params.size() == 0) { throw new TemplateException("params can not be empty", env); } int count = 0; String excludeStr = null; // 处理传入的参数 for (Object key : params.keySet()) { String name = (String) key; if (name.equalsIgnoreCase("count")) { if (params.get(key) instanceof TemplateNumberModel) count = ((TemplateNumberModel) params.get(key)).getAsNumber().intValue(); else throw new TemplateException("count param must be number", env); } if (name.equalsIgnoreCase("exclude")) { if (params.get(key) instanceof TemplateScalarModel) excludeStr = ((TemplateScalarModel) params.get(key)).getAsString(); else throw new TemplateException("execlude param must be string", env); } } List
chanleList = chanelDao.loadAll(); List
list = new ArrayList<>(); for (int i = 0; i < count && i < chanleList.size(); i++) { if (chanleList.get(i).getName().equals(excludeStr)) continue; list.add(chanleList.get(i)); } env.setVariable("chllist", ObjectWrapper.DEFAULT_WRAPPER.wrap(list)); if (body != null) { body.render(env.getOut()); } }}

在freemarker中配置

需要绑定该指令为cms_chanel_list

...    
...

转载地址:http://zxhrb.baihongyu.com/

你可能感兴趣的文章
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
Mysql出现Table 'performance_schema.session_status' doesn't exist
查看>>
MySQL innert join、left join、right join等理解
查看>>
vivado模块封装ip/edf
查看>>
sdc时序约束
查看>>
Xilinx Jtag Access/svf文件/BSCANE2
查看>>
NoC片上网络
查看>>
开源SoC整理
查看>>
【2020-3-21】Mac安装Homebrew慢,解决办法
查看>>
influxdb 命令行输出时间为 yyyy-MM-dd HH:mm:ss(年月日时分秒)的方法
查看>>
已知子网掩码,确定ip地址范围
查看>>
判断时间或者数字是否连续
查看>>
docker-daemon.json各配置详解
查看>>
Docker(一)使用阿里云容器镜像服务
查看>>
Docker(三) 构建镜像
查看>>
FFmpeg 是如何实现多态的?
查看>>
FFmpeg 源码分析 - avcodec_send_packet 和 avcodec_receive_frame
查看>>
FFmpeg 新旧版本编码 API 的区别
查看>>