freemarker基础

联合使用指令

在页面也可以多次使用指令,而且指令间可以相互嵌套,正如在 HTML 元素中嵌套使用

标签一样。下面的代码会遍历动物集合,用大号字体来打印大型动物的名字。

<p>We have these animals:
<table border=1>
<tr><th>Name<th>Price
<#list animals as being>
<tr>
<td>
<#if being.size == "large"><font size="+1"></#if>
${being.name}
<#if being.size == "large"></font></#if>
<td>${being.price} Euros
</#list>
</table
注意到 FreeMarker 并不解析 FTL 标签外的文本,插值和注释,当条件不满足时它也会

忽略所有嵌套的 font 标签。

处理不存在的变量

可以在变量名后面通过放置??来询问 FreeMarker 一个变量是否存在。将它和 if
指令合并,那么如果 user 变量不存在的话将会忽略整个问候代码段:
关 于 多 级 访 问 的 变 量 , 比 如 animals.python.price , 书 写 代 码 :

<#if user??><h1>Welcome ${user}!</h1></#if>
animals.python.price!0,仅当 animals.python 存在而仅仅最后一个子变
量 price 可能不存在(这种情况下我们假设价格是 0)。如果 animals 或者 python
不存在,那么模板处理过程将会以“未定义的变量”错误而停止。为了防止这种情况的发生,
可以这样来书写代码(animals.python.price)!0。这种情况下当 animals 或
python 不存在时表达式的结果仍然是 0。对于??也是同样用来的处理这种逻辑的:

animals.python.price??对比(animals.python.price)??来看

freemarker空值处理方法 

配置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)

举一反三,其他属性也可以用类似方法进行设置。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值