micronaut

Can Micronaut render a view with a template supplied at runtime?


Instead of placing a view template in the src/main/resources/views directory, can we supply template at a runtime, for example getting a template from a database and then rendering a model with that view template?

I didn't find anything in the docs about non-file-based view schemes.


Solution

  • Template engines supported by Micronaut such as Thymeleaf, Velocity, Jte, … are traditionally file based. Therefore the answer to your question is «no, that is not possible», if you stick with the out of the box template engine integration.

    Yes, you can if you implement your custom view renderer. All it takes is a custom io.micronaut.views.ViewsRenderer bean that is implemented by you and which reads the template source from the database by its viewName.

    public interface ViewsRenderer<T, R> extends Ordered {
    
        /**
         * @param viewName view name to be rendered
         * @param data     response body to render it with a view
         * @param request  HTTP request
         * @return A writable where the view will be written to.
         */
        @NonNull Writable render(@NonNull String viewName,
                                 @Nullable T data,
                                 @Nullable R request);
    
        /**
         * @param viewName view name to be rendered
         * @return true if a template can be found for the supplied view name.
         */
        boolean exists(@NonNull String viewName);
    }