package org.bee.tl.samples; import java.util.Arrays; import java.util.Date; import org.bee.tl.core.GroupTemplate; import org.bee.tl.core.Template; public class MissingValue { public static void main(String[] args) throws Exception { String input = "${cat.parent.name!'无'}" ; GroupTemplate group = new GroupTemplate(); group.config("<%", "%>", "${", "}"); Template template = group.getStringTemplate(input); Cat cat1 = new Cat("huahua",new Date(),null); template.set("cat", cat1); String output =template.getTextAsString(); System.out.println(output); } } \
点击此查看Cat类
在占位符输出的时候,可以在变量引用后加上!加上字符串,表示当变量引用为Null的时候,输出!后面的字符串,如cat.parent.name!'',表示如果parent为null或者cat为空的时候输出空字符串
还有一种安全输出方法,无论占位符抛出什么异常,都不作输出,使用!(), 如!(cat.parent,name),使用此安全输出,在错误情况下,会降低性能