有没有一种方法可以检测Freemarker模板中设置为NaN的数字(java double)?
基本上我想做类似的事情:
<#if val?is_nan>
-
<#else>
${val}
</#if>
我尝试将其转换为字符串,然后检查
\uFFFD
字符,但在此处无法进行正确的比较。我的印象是我的问题来自于方式,我将数据交给处理
Map<String, Object> root = new HashMap<String, Object>();
root.put("var", objectToRender);
template.process(root, out);
其中
objectToRender
是我使用的数据结构。也许我需要为双重处理设置一些特殊标志?
最佳答案
更新:从FreeMarker 2.3.20开始,您只需编写val?is_nan
即可。对于旧版本,请参见下文...
没有n?is_nan
,但是您可以创建自己的方法用作isNaN(n)
:
import java.util.List;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
public class IsNaNMethod implements TemplateMethodModelEx {
public static final IsNaNMethod INSTANCE = new IsNaNMethod();
public Object exec(@SuppressWarnings("rawtypes") List args)
throws TemplateModelException {
if (args.size() != 1) {
throw new TemplateModelException("isNaN needs exactly 1 arguments!");
}
Object arg = args.get(0);
if (arg == null) {
throw new TemplateModelException(
"The argument to the isNaN method must not be null!");
}
if (!(arg instanceof TemplateNumberModel)) {
throw new TemplateModelException(
"The argument to the isNaN method must be a number! " +
"(The class of the value was: " + arg.getClass().getName() + ")");
}
Number n = ((TemplateNumberModel) arg).getAsNumber();
if (n instanceof Double) {
return ((Double) n).isNaN()
? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
} else if (n instanceof Float) {
return ((Float) n).isNaN()
? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
} else {
return TemplateBooleanModel.FALSE;
}
}
}
将
IsNaNMethod.INSTANCE
作为“isNaN”放入数据模型中(或放入所有带有config.setSharderVariable
的数据模型中),或仅将其放入带有#include
的#import
-d / <#assign isNaN = "com.example.IsNaNMethod"?new()>
-ed模板中。
关于freemarker - 在Freemarker中检测数字值的NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10946445/