---
title: "freemarker的模板标签获取"
author: "qepipnu"
date: "2011-03-28T13:23:13Z"
tags: []
categories: ["编程语言"]
slug: "freemarker"
draft: false
lastmod: "2011-03-28T13:23:13Z"
id: 977288
url: "https://qepipnu.iteye.com/blog/977288"
---

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());   
                }   
}