如何在不注入的情况下动态加载quarkus qute模板?
How to load quarkus qute template dynamic without inject?
我遇到了以下问题:我有一项服务,我想在其中使用 qute 动态呈现模板。我目前不知道谁的名字(因为它们是通过端点传递的)。
不幸的是,Quarkus 本身并没有提供说“Template t = new Template()”的可能性......你总是必须在 class 的开头通过注入来定义它们。经过长时间的寻找和思考,我有以下解决方案:
解决方案是注入 Quarkus 模板引擎而不是模板。引擎可以直接渲染一个模板....然后我们只需要读取我们的模板文件作为一个字符串(Java 11 可以读取Files.readString(路径,编码))并用我们的数据映射渲染它.
@Path("/api")
public class YourResource {
public static final String TEMPLATE_DIR = "/templates/";
@Inject
Engine engine;
@POST
public String loadTemplateDynamically(String locale, String templateName, Map<String, String> data) {
File currTemplate = new File(YourResource.class.getResource("/").getPath() + TEMPLATE_DIR + locale + "/" + templateName + ".html"); // this generates a String like <yourResources Folder> + /templates/<locale>/<templateName>.html
try {
Template t = engine.parse(Files.readString(currTemplate.getAbsoluteFile().toPath(), StandardCharsets.UTF_8));
//this render your data to the template... you also could specify it
return t.data(data.render());
} catch (IOException e) {
e.printStackTrace();
}
return "template not exists";
}
}
我遇到了以下问题:我有一项服务,我想在其中使用 qute 动态呈现模板。我目前不知道谁的名字(因为它们是通过端点传递的)。 不幸的是,Quarkus 本身并没有提供说“Template t = new Template()”的可能性......你总是必须在 class 的开头通过注入来定义它们。经过长时间的寻找和思考,我有以下解决方案:
解决方案是注入 Quarkus 模板引擎而不是模板。引擎可以直接渲染一个模板....然后我们只需要读取我们的模板文件作为一个字符串(Java 11 可以读取Files.readString(路径,编码))并用我们的数据映射渲染它.
@Path("/api")
public class YourResource {
public static final String TEMPLATE_DIR = "/templates/";
@Inject
Engine engine;
@POST
public String loadTemplateDynamically(String locale, String templateName, Map<String, String> data) {
File currTemplate = new File(YourResource.class.getResource("/").getPath() + TEMPLATE_DIR + locale + "/" + templateName + ".html"); // this generates a String like <yourResources Folder> + /templates/<locale>/<templateName>.html
try {
Template t = engine.parse(Files.readString(currTemplate.getAbsoluteFile().toPath(), StandardCharsets.UTF_8));
//this render your data to the template... you also could specify it
return t.data(data.render());
} catch (IOException e) {
e.printStackTrace();
}
return "template not exists";
}
}