【问题标题】:How to load quarkus qute template dynamic without inject?如何在不注入的情况下加载 quarkus qute 模板动态?
【发布时间】:2021-08-19 08:15:06
【问题描述】:

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

【问题讨论】:

    标签: java templates dynamic quarkus quarkus-qute


    【解决方案1】:

    解决方案是注入 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";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-04
      • 2021-12-19
      • 2021-01-11
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多