关于FreeMarker自定义TemplateDirectiveModel
java代码如下:
import freemarker.core.Environment; import freemarker.template.ObjectWrapper; import freemarker.template.TemplateDirectiveModel; /** * FreeMarker自定义宏 * 获取App下载排行列表 * 参数包括 length(列表长度) mtypeCode(主类型代码) typeCode(小类型代码) rankMode(排行模式1、2、3) * @author shannon * */ public class FMAppRankDirective implements TemplateDirectiveModel { @Resource(name = "appRankService") private AppRankService appRankService; @SuppressWarnings("unchecked") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { //DirectiveUtils是借用jeecms项目中的工具类,主要是因为它集成了一些异常处理功能, //其实完全可以不用它,params是个Map,自己通过key取值就可以了,做一下空值判断 Integer length = DirectiveUtils.getInt("length", params); Integer mtypeCode = DirectiveUtils.getInt("mtypeCode", params); Integer typeCode = DirectiveUtils.getInt("typeCode", params); Integer rankMode = DirectiveUtils.getInt("rankMode", params); ArrayList<App> rankList = appRankService.getRankList(length, mtypeCode, typeCode, rankMode); env.setVariable("appRankList", ObjectWrapper.DEFAULT_WRAPPER.wrap(rankList)); if (body != null) { body.render(env.getOut()); } } }
页面引用有多种方法:
一:
<bean id="fp" class="xxxx.tag.FMAppRankDirective"></bean> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> 此处省略 <property name="freemarkerVariables"> <map> <entry key="fp" value-ref="fp"/> </map> </property> </bean>
然后页面直接用<@fp的方式调用,
二:在页面上直接导入,如:
<#assignfp="xxxx.tag.FMAppRankDirective"?new()>
推荐用第一种
相关推荐
81314797 2020-11-18
89314493 2020-11-03
81941231 2020-09-17
thisisid 2020-09-09
如狼 2020-08-15
82384399 2020-06-16
86384798 2020-05-12
80183053 2020-05-02
86384798 2020-04-26
86384798 2020-04-11
rionchen 2020-04-09
86384798 2020-04-07
86384798 2020-04-04
80183053 2020-03-07
87201943 2020-03-06
83961233 2020-02-26
87201943 2020-02-21