寫這篇文章主要是考慮到如下問題會困擾大家
- java.io.FileNotFoundException: Template xxx.ftl not found.
- 如何讓模板中支持原生的<#include “common.ftl”>
- 如何在編輯ftl檔案中變數的時候能夠有有效的提示(此處使用的是idea)
解決方案
首先,看下TemplateLoader實作類有哪些

對于打jar包后的讀取ftl檔案需要通過流讀取檔案或者通過URL
此處就簡單的以StringTemplateLoader為例簡單介紹,直接貼代碼演示
/**
* 初始化include模板
*
* @param templateContent
* @param stringTemplateLoader
*/
public static void initCommonTemplate(String templateContent, StringTemplateLoader stringTemplateLoader) {
// 按指定模式在字串查找
String pattern = "(?<=<#include\\s\")(.*?)(?=\"\\s*>)";
// 創建 Pattern 物件
Pattern r = Pattern.compile(pattern);
// 現在創建 matcher 物件
Matcher m = r.matcher(templateContent);
while (m.find()) {
String childTemplateName = "";
String group = m.group();
if (group.startsWith("/")) {
childTemplateName = group.substring(1);
} else {
childTemplateName = group;
}
stringTemplateLoader.putTemplate(childTemplateName, ResourceHelper.getString(group));
}
}
public static void main(String[] args) throws Exception{
//region 初始化模板程序
Configuration ftlConifg = new Configuration(Configuration.VERSION_2_3_29);
String path = "a.ftl";
//獲取檔案內容
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
String content = new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
//將其填充到stringTemplateLoader中
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate(path,content);
//填充content中include的模板
initCommonTemplate(content,stringTemplateLoader);
ftlConifg.setTemplateLoader(stringTemplateLoader);
//endregion
//region 獲取填充資料后的模板
//讀取模板
Template template = ftlConifg.getTemplate(path, StandardCharsets.UTF_8.toString());
//填充資料
Object data = new Object();
var out = new StringWriter();
template.process(Map.of("item", data), out);
String result = out.toString();
//endregion
}
此外補充一點(如何在編輯ftl檔案中變數的時候能夠有有效的提示)
在ftl檔案開頭加上如下內容,編輯的時候會有代碼提示
<#-- @ftlvariable name="item" type="class路徑" -->
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/261719.html
標籤:java
