在FreeMarker3.8-版本中实现FreeMarker3.8+的!功能

       FreeMarker3.8中引入了一个非常实用的!功能,在FreeMarker3.8-中,如果要显示类似${user.phone.areacode}的值,需要层层判断是否为NULL,譬如如上的表达式一般在FTL中需要写成<#if user?exists><#if user.phone?exists><#if user.phone.areacode?exists>${user.phone.areacode}},不胜烦琐,而在FreeMarker3.8中可以使用${(user.phone.areacode)!}达到同样的目的。那么如果使用的是FreeMarker3.8-,有什么可选的替代方案呢?下面是我想的一种解决方案

java 代码
 
  1. /** 
  2.  * @author Ray (ayufox@gmail.com) 
  3.  */  
  4. public class EmptyTemplateHashModel implements TemplateHashModel, TemplateScalarModel  
  5. {  
  6.     public final static EmptyTemplateHashModel INSTANCE = new EmptyTemplateHashModel();  
  7.   
  8.     public TemplateModel get(String n) throws TemplateModelException  
  9.     {  
  10.         return INSTANCE;  
  11.     }  
  12.   
  13.     public boolean isEmpty() throws TemplateModelException  
  14.     {  
  15.         return true;  
  16.     }  
  17.   
  18.     public String getAsString() throws TemplateModelException  
  19.     {  
  20.         return "";  
  21.     }  
  22. }  
  23.          
  24.       
  25. /** 
  26.  * @author Ray (ayufox@gmail.com) 
  27.  */  
  28. public class DelegatingTemplateHashModel implements TemplateHashModel  
  29. {  
  30.     private TemplateHashModel target;  
  31.   
  32.     public DelegatingTemplateHashModel(TemplateHashModel target)  
  33.     {  
  34.         this.target = target;  
  35.     }  
  36.   
  37.     public TemplateModel get(String name) throws TemplateModelException  
  38.     {  
  39.         TemplateModel model = this.target.get(name);  
  40.         if (model == null)  
  41.         {  
  42.             return EmptyTemplateHashModel.INSTANCE;  
  43.         }  
  44.         if (model instanceof TemplateHashModel)  
  45.         {  
  46.             return new DelegatingTemplateHashModel((TemplateHashModel) model);  
  47.         }  
  48.         return model;  
  49.     }  
  50.   
  51.     public boolean isEmpty() throws TemplateModelException  
  52.     {  
  53.         return this.target.isEmpty();  
  54.     }  
  55. }  

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值