0

我遇到了以下问题:我有一项服务,我想使用 qute 动态呈现模板。我目前不知道谁的名字(因为它们是通过端点传递的)。不幸的是,Quarkus 本身并没有提供说“Template t = new Template()”的可能性......你总是必须在类的开头通过注入来定义它们。经过长时间的搜索和思考,我有以下解决方案:

4

1 回答 1

0

解决方案是注入 Quarkus 模板引擎而不是模板。引擎可以直接渲染模板......然后我们只需将模板文件读取为字符串(Java 11 可以读取 Files.readString(path, encoding))并使用我们的数据映射渲染它。

@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";
    }
}
于 2021-08-19T08:15:06.107 回答