freemarker的模板标签获取

In FreeMarker 2.2, Template has an undocumented method for examining the parsed template: getRootTreeNode 使用freemarker模板引擎进行传统的开发有个固定的模式就是我们知道模板上有哪些标签,然后我们会获取这些标签的数据来进行data+model的组合。但是如果模板上的标签名字或者个数不确定的话,那么我们就需要知道模板上到底有那些标签了。这样做的好处有以下几个方面:

1、我们可以根据模板实际拥有的标签来进行数据获取,避免了将整个系统的标签都穷举一遍,分别查取数据

2、我们可以分析获取到的标签名字,根据标签名字来做逻辑

但是freemarker2.2官方的faq列表的第26项中确是明确的说不想支持这个功能。但是又很猥琐的提出了一个解决方案,就是将模板的各个数据项进行了拆分。提供一个半公开的访问接口。

view plaincopy to clipboardprint?
In FreeMarker 2.2, Template has an undocumented method for examining the parsed template: getRootTreeNode
In FreeMarker 2.2, Template has an undocumented method for examining the parsed template: getRootTreeNode

通过查看Template的源代码发现,她将那个模板标签封装的是十分严密,对外提供的方法和类都是包内可见,实在是让人难以入手。最后不得不想个歪招将我们要的标签给打印出来了。如下

view plaincopy to clipboardprint?
Template t = getFreeMarkerCFG().getTemplate(templateFileName);
//获取所有的标签项
TemplateElement te=t.getRootTreeNode();

for(Enumeration children = te.children(); children.hasMoreElements();){
Object obj=children.nextElement();
if("class freemarker.core.DollarVariable".equals(obj.getClass().toString())){
System.out.println(obj.toString());
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值