freemark 笔记

最近学习了一下Freemarker对于大型门户来说,日访问量如果上万的话,首页内容比较多的话,优化方法除了采用连接池、Css Sprite、Js压缩之外,非常有必要对首页进行静态化的处理,使用Struts2就会接触到Freemarker这个非常好用的静态化工具,搞了半天终于把现在进行的首页进行全静态化。下次再把Freemarker的源码通读一遍 
Freemarker学习笔记: 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
1) 空值Null配置处理 
a.通过Configuration设置。Configuration cfg = new Configuration(); cfg.setClassicCompatible(true);//设置属性 
b.通过Eviroment设置。 
   Environment env = template.createProcessingEnvironment(root, out); 
   env.setClassicCompatible(true); 
c.通过ftl设置:在ftl前加入<!--#setting classic_compatible=true--> 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
2) 空值Null判断 
${(category.parentCategory.id)!0}   加括号代表category, category.parentCategory, category.parentCategory.id这三个都会进行判断;  不加括号只判断category.parentCategory.id是否为null 
<#if list?exists && list.size != 0 > 
空值判断:${book.name?if_exists }, 
${book.name?default(‘xxx’)}//默认值xxx 
${ book.name!"xxx"}//默认值xxx 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
3) 时间格式化显示 
<#assign datetimeformat="yyyy-MM-dd HH:mm:ss zzz"> 
<lastBuildDate>${date?string(datetimeformat)}</lastBuildDate> 
<pubDate>${date?string(datetimeformat)}</pubDate> 

数字格式:${book?string.number}--20 
${book?string.currency}--<#-- $20.00 --> 
${book?string.percent}—<#-- 20% --> 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
4) 字符串截取substring,注意substring中括号的位置 
<#if res1.NAME?length<12> 
${res1.NAME} 
<#else> 
${res1.NAME?substring(0,12)} 
</#if> 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
5) String内置的JavaScript转换: js_string 
用途:用于JavaScript转义,转换',",换行等特殊字符 
模板: 
<script> 
alert("${errorMessage?js_string}"); 
</script> 
输出: 
<script> 
alert("Readonly\'s pet name is \"Cross Bone\""); 
</script> 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
6) 内置的默认值处理:default 
用途: 用于处理默认值 
模本: 
User: ${userLogin.name?default("Anonymous")} 
<td>${(employee.department.manager.name)?default(" ")}</td> 

输出: 
User: Anonymous 
<td> </td> 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
7) Sequence内置的计数器: xxx_index 
用途:显示序号 
模板: 
<#list employees as e> 
${e_index}. ${e.name} 
</#list> 

输出: 
1. Readonly 
2. Robbin 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
8) 插入布尔值: 
<#assign foo=ture /> 
${foo?string("yes","no")} <#-- yes --> 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
9) Sequence内置的分段器: chunk 
用途:某些比较BT的排版需求 
模板: 
<#assign seq = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']> 
<#list seq?chunk(4) as row> 
<ul> 
<li><#list row as cell>${cell} </#list></li> 
</ul> 
</#list> 
<#list seq?chunk(4, '-') as row>  // 不够4个的以“-”填充 
<tr> 
<td><#list row as cell>${cell} </#list></td> 
</tr> 
</#list> 

输出: 
<ul> 
<li>a</li> 
<li>b</li> 
<li>c</li> 
<li>d</li> 
</ul> 
<ul> 
<li>e</li> 
<li>f</li> 
<li>g</li> 
<li>h</li> 
</ul> 
<ul> 
<li>i</li> 
<li>j</li> 
</ul> 
<tr> 
<td>a</td> 
<td>b</td> 
<td>c</td> 
<td>d</td> 
</tr> 
<tr> 
<td>e</td> 
<td>f</td> 
<td>g</td> 
<td>h</td> 
</tr> 
<tr> 
<td>i</td> 
<td>j</td> 
<td>-</td> 
<td>-</td> 
</tr>



尊重原创:http://awaitdeng.iteye.com/blog/949496
<think>我们正在处理用户关于Freemarker模板使用教程和示例的请求。根据引用内容,Freemarker是一个模板引擎,用于生成文本输出(如HTML、配置文件等)。它结合模板文件(包含静态内容和动态标记)和数据模型来生成输出。 我们将按照以下结构组织回答:1.Freemarker模板基础介绍2.模板文件结构3.常用语法(变量、条件、循环等) 4.示例代码5.实际应用场景同时,根据系统指令,我们需要在行内数学表达式使用$...$,独立公式使用$$...$$(但本问题不涉及数学公式,所以主要关注代码和文字描述)。另外,我们将在回答末尾生成相关问题。注意:引用内容中提供了部分信息,我们将结合这些信息进行回答,并在适当位置添加引用标识。 现在开始构建回答:</think>### Freemarker模板使用教程与示例 #### 一、基础概念 Freemarker是一款**模板引擎**,通过将模板文件(包含静态内容+特殊标记)与数据模型结合,动态生成文本输出(HTML/配置文件/代码等)[^4]。核心组件: 1. **模板文件**(.ftl):混合静态内容和动态指令 2. **数据模型**(Java对象/Map):提供动态数据 3. **配置引擎**(`Configuration`):管理模板加载和设置 #### 二、模板文件结构 ```html <!DOCTYPE html> <html> <head> <title>${pageTitle}</title> <!-- 插值表达式 --> </head> <body> <#-- 注释:不会输出到结果 --> <#if user.loggedIn> <!-- 指令 --> 欢迎, ${user.name}! <#else> <a href="/login">登录</a> </#if> <ul> <#list products as product> <!-- 循环指令 --> <li>${product.name} - 价格: ¥${product.price?string("0.00")}</li> </#list> </ul> </body> </html> ``` #### 三、核心语法详解 1. **插值表达式** `${variable}` 输出变量值,支持运算符: `${price * 1.08}` <!-- 计算含税价 --> `${name!"默认值"}` <!-- 空值处理 --> 2. **常用指令** ```html <#-- 条件判断 --> <#if score >= 90> 优秀 <#elseif score >= 60> 合格 <#else> 不合格 </#if> <#-- 循环遍历 --> <#list ["苹果", "香蕉", "橙子"] as fruit> ${fruit?index + 1}. ${fruit?cap_first} </#list> ``` 3. **函数与处理** ```html ${date?string("yyyy-MM-dd")} <!-- 日期格式化 --> ${text?upper_case} <!-- 转大写 --> ${htmlContent?no_esc} <!-- 禁用HTML转义 --> ``` #### 四、Java集成示例 ```java // 配置模板引擎 Configuration cfg = new Configuration(Configuration.VERSION_2_3_31); cfg.setDirectoryForTemplateLoading(new File("/templates")); // 模板路径[^2] // 准备数据模型 Map<String, Object> data = new HashMap<>(); data.put("pageTitle", "商品列表"); data.put("products", Arrays.asList( new Product("手机", 2999), new Product("笔记本", 5999) )); // 处理模板 try (Writer out = new FileWriter("output.html")) { Template template = cfg.getTemplate("product_list.ftl"); template.process(data, out); // 生成最终文件 } ``` #### 五、高级特性 1. **宏定义**(可复用组件) ```html <#macro userCard user> <div class="card"> <h3>${user.name}</h3> <p>邮箱: ${user.email}</p> </div> </#macro> <@userCard user=currentUser /> <!-- 调用宏 --> ``` 2. **错误处理** ```html <#attempt> 可能出错的代码 <#recover> 错误处理逻辑 </#attempt> ``` 3. **包含子模板** ```html <#include "header.ftl"> ``` #### 六、典型应用场景 1. Web开发:动态生成HTML页面(替代JSP) 2. 代码生成:自动创建Controller/Entity类[^2] 3. 报表系统:导出格式化Excel/PDF 4. 邮件模板:个性化邮件内容 > 最佳实践:将模板文件存放在`resources/templates`目录,通过`ClassTemplateLoader`加载[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值