mEEzy
mEEzy

Reputation: 145

Render a variable as HTML in Java Spring Thymeleaf

In my .java file, I have

@RequestMapping(value = "/page1", method = RequestMethod.GET)
public String callback(@RequestParam(name = "token") String token, Model model){
    //do something with token
    //result variable is either 
    //"<p style=\"color:red;font-size:20px\"><strong>fail</strong></p>" 
    //or 
    //"<p style=\"color:green;font-size:20px\"><strong>pass</strong></p>"
    model.addAttribute("result", result);
    return "page1";

in my page1.html file:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Page1</title>
</head>
<body>
<p th:text="'here is the result: ' + ${result}"></p>
</body>
</html>

Right now, my page1 displays:

here is the result: <p style="color:green;font-size:20px"><strong>pass</strong></p>

Is it possible to render my result variable as html so that my page1 displays a big green pass? Are there other formatting options rather than th:text + ${var}?I'm using spring boot and thymeleaf. I'm trying not to use javascript for this.

Something like this this, but for java

Upvotes: 1

Views: 3047

Answers (2)

This is a bad mixture of presentation and semantics at the controller level, and a bad mixture of content and style at the HTML level. Instead, use a boolean attribute for result and use th:if or similar to switch the HTML content in your template, and avoid inline styles in favor of something like class="success".

Upvotes: 2

stacker
stacker

Reputation: 4475

use this one:

th:utext="'here is the result: ' + ${result}"

Upvotes: 2

Related Questions