freemarker - 在Freemarker中检测数字值的NaN

标签 freemarker

有没有一种方法可以检测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/

相关文章:

boolean - 使用 Freemarker 将字符串转换为 boolean 值

java - 在 freemarker 中切换枚举

java - Freemarker - <#if ??> 似乎无法识别空对象

java - 使用 Spark 从多个动态复选框请求查询

dictionary - 如何以 map 作为参数调用Freemarker宏?

java - 如何在 spring mvc 中使用 freemarker 消息?

java - 如何删除 FreeMarker 模板中的文件扩展名

spring - 将图像添加到邮件的 freemarker 模板中?

java - 检查freemarker中两个字符串是否相等,其中一个字符串包含&符号

java - 在 freemarker 中遍历 hashmap