【问题标题】:Freemarker The following has evaluated to null or missingFreemarker 以下已评估为 null 或缺失
【发布时间】:2021-12-22 03:55:20
【问题描述】:

我在评估 freemarker 期间遇到以下错误。但是,此错误仅仅在构建中显示,而不在 IDE 中显示。

{"code":"NoApplicableCode","description":"处理模板 freemarkerTest.ftl 时发生错误\n以下已评估为 null 或缺失:\n==> loadJSON

//freemarker function
<#assign keywordsJSON = "${loadJSON('path/to/file/random.json')}">
//function for creating freemarker function
protected void addUtilityFunctions(String baseURL, Map<String, Object> model) {
    model.put("loadJSON", parseJSON());
}

private TemplateMethodModelEx parseJSON() {
    return arguments -> loadJSON(arguments.get(0).toString());
}

private String loadJSON(String filePath) {
    JSONParser parser = new JSONParser();
    try {
            File file = fileFinder.findFile(filePath);
            if (file == null) {
                LOGGER.warning("File is outside of data directory");
                throw new RuntimeException(
                        "File " + filePath + " is outside of the data directory");
            }
            return parser.parse(new FileReader(file.getPath())).toString();
        } catch (Exception e) {
            LOGGER.warning("Failed to parse JSON file " + e.getLocalizedMessage());
        }
        LOGGER.warning("Failed to create a JSON object");
        return "Failed to create a JSON object";
    }

【问题讨论】:

  • addUtilityFunctions 的电话在哪里?当然在某些情况下它不会被调用。
  • 与您的问题无关,但有两个简化:1. 只需写&lt;#assign keywordsJSON = loadJSON('path/to/file/random.json')&gt;;你不想要"${...}" 的东西。 2.如果参数必须是字符串,实现TemplateMethodModel而不是TemplateMethodModelEx。 (如果你实现了TemplateMethodModelEx,那么检查args(0)是否是TemplateScalarModel,如果它被转换成那个,然后调用getAsString()。)
  • 我确信 addUtilityFunctions 被调用是因为除了“loadJSON”之外的所有其他函数都在工作并且它们都以相同的方式调用,这是一个私有函数和 lambda 引用。我还尝试了您简化表达式的方法,但它不起作用,但更优雅。感谢那。但问题仍然存在。你还有什么想法吗? @ddekany
  • 您的意思是在addUtilityFunctions 内的model 中添加其他值,并且可以从模板中访问它们?那是唯一将这些添加到模型中的地方吗?因为没有任何功能可以让 FreeMarker 报告 loadJSON 丢失,而实际上它在调用模板时位于 model 中。
  • 另外,我假设您粘贴的错误消息相当完整。好像不是The following has evaluated to null or missing: loadJSON('path/to/file/random.json')。因为如果确实只是缺少 loadJSON,那么 lambda 是否运行良好等等都无关紧要。那里没有任何名称为 loadJSON 的对象。

标签: java maven freemarker


【解决方案1】:

问题在于不同的 freemarker 模板有不同的功能。我没有把函数放到正确的地方。问题中的所有语法和函数调用都是正确的。

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 2016-02-29
    • 2016-06-18
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2016-03-08
    相关资源
    最近更新 更多