【发布时间】: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. 只需写
<#assign keywordsJSON = loadJSON('path/to/file/random.json')>;你不想要"${...}"的东西。 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