難道每個變量都要加入一個判斷?就像struts中醜陋的<empty>標籤?既然是模板引擎,就要靈活,何必來那麼多限制?
還好,freemarker至少提供瞭解決辦法,否則我只好選擇其它引擎了。
freemarker中空值的多種處理方法:
1.按照freemarker的規範,老老實實的判斷是否有空值,有空值怎麼處理。這在某種時候是有用的。格式:${empty!"EmptyValue of fbysss"}
比如值爲空時,你可以給出一個友好的說明,但是很多的變量都要這麼說明,未免太麻煩了。
2.<#escape x as x!""></#escape>可以對所有的變量進行空值處理,這裏是全部替換爲空字符串。當然也可以替換爲其它字符串。
如果其中某些變量不需要這種替換,可以加入<#noescape></#noescape>標籤。
3.屬性配置方法:
配置classic_compatible=true可以滿足一般需要。默認情況變量爲null則替換爲空字符串,如果需要自定義,寫上${empty!"EmptyValue of fbysss"}的形式即可
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-->;
d.通過Spring配置文件設置
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="freemarkerSettings">
<props>
<prop key="classic_compatible">true</prop>
</props>
</property>
</bean>
e.class目錄下添加freemarker.properties文件:加入classic_compatible=true
(需要struts2或spring)