1

I had the following problem: I have a service where I want to dynamically render templates using qute. Whose names I don't currently know (because they are passed via the endpoint). Unfortunately Quarkus itself doesn't give the possibility to say "Template t = new Template()".... You always have to define them via inject at the beginning of a class. After a long time of searching and thinking about it, I have the following solution:

1 Answers1

2

The solution is to inject the Quarkus Template Engine instead of a Template. The Engine could render a template directly.... Then we only have to read our template file as a String (Java 11 can read Files.readString(path, encoding)) and render it with our data map.

@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";
    }
}