freemarker如何判空容错

freemarker如何判空容错呢? 

freemark是什么? 
freemark是java后台的模板语言 
如果模板使用vm中没有的变量就会报错 
怎么办呢? 
针对使用场景分为两种:

(1)用于页面显示

<span class="info-date">${old_order_startTime!'--'}

 使用感叹号,如果没有设置值,就使用感叹号后面的”–”为默认值 

实例: 

 

 

(2)用于if判断

<#if orderInfo.couponList??>
                <#list orderInfo.couponList as ite>
                    <p>- 红包:&nbsp;
                        ¥${ite.couponPay}</p>
                </#list>
            </#if>

 使用形式概览:unsafe_expr??或(unsafe_expr)??

这个操作符告诉我们一个值是否存在。基于这种情况,结果是 true 或 false。 示例如下,假设并没有名为 mouse 的变量:

<#if mouse??> Mouse found

<#else>

No mouse found </#if>

Creating mouse...

<#assign mouse = "Jerry"> <#if mouse??>

Mouse found <#else>

No mouse found </#if>

 输出为: 

No mouse found

Creating mouse…

Mouse found 
访问非顶层变量的使用规则和默认值操作符也是一样的,即 product.color??和 (product.color)??

(3)判断时也可以使用默认值



 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>freemarker demo</title>
</head>
<body>
${username} <br />
${age}<br />
${sex!} <br>
<#if (sex!23) ==23 >
ok
<#else>
no
</#if>
</body>
</html>

(4)比较时必须是同类型的比较

int 和string 类型比较就会报错

freemarker 开发文档见附件

猜你喜欢

转载自hw1287789687.iteye.com/blog/2271501