Search code examples
springspring-bootthymeleaf

Get Raw Html From the controller Spring thymeleaf


I have a controller that create model attribute and passes to the view "partial.html" to generate output

partial.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home page</title>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<p>
    <span th:text="'Today is: ' + ${message}"></span>
</p>
</body>
</html>

and inside a controller method

model.addAttribute("message", search);

How to do I get Htlm Output to a string inside controller method? like this

String htmlOutput="from partial.html";

Solution

  • Let's say you have a HTML file with two variable name and todayDate.
    You want to process it and want to store it in a string / database / AWS S3.

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
            <p>Hello</p>
            <p th:text="${name}"></p>
            <p th:text="${todayDate}"></p>
        </body>
    </html>
    

    Your HTML file location is src/main/resources/templates/home.html

    By using the below function you can get the final processed HTML as:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
            <p>Hello</p>
            <p>Manoj</p>
            <p>30 November 2019</p>
        </body>
    </html>
    
    import org.thymeleaf.context.Context;
    
    @GetMapping("/")
        public void process() {
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
            templateResolver.setPrefix("templates/");
            templateResolver.setCacheable(false);
            templateResolver.setSuffix(".html");
            templateResolver.setTemplateMode("HTML");
    
            // https://github.com/thymeleaf/thymeleaf/issues/606
            templateResolver.setForceTemplateMode(true);
    
            templateEngine.setTemplateResolver(templateResolver);
    
            Context ctx = new Context();
    
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
            Calendar cal = Calendar.getInstance();
    
            ctx.setVariable("todayDate", dateFormat.format(cal.getTime()));
            ctx.setVariable("name", "Manoj");
            final String result = templateEngine.process("home", ctx);
            System.out.println("result:" + result);
        }