I'm new in thymeleaf and I try to create a template. My problem is this code:
<p th:utext="${story.info}" >
</p>
I want to get this output:
<p> <h1> Text</h1> ... </p>
But this is the real output:
<p> </p><h1> Text</h1> ...
I have to do to adjust the text to the right position
Thanks in advance.
You have 2 options to achieve this. first, you might want to use th:remove tag along with th:utext.
In thymeleaf, th:remove can behave in five different ways, depending on its value:
all: Remove both the containing tag and all its children.
body: Do notremove the containing tag, but remove all its children.
tag: Remove the containing tag, but do not remove its children.
all-but-first: Remove all children of the containing tag except the first one.
none : Do nothing. This value is useful for dynamic evaluation.
Second, send the html escaped string from the backend. This approach may need some extra processing though. Thnx
Controller class
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.ServletContext;
import java.util.Locale;
@Controller
public class NavigationController {
private static final Logger logger = LoggerFactory.getLogger(NavigationController.class);
@Autowired
private ServletContext servletContext;
@GetMapping({"/", "/index"})
public String defaultPage(final Model model, final Locale locale){
model.addAttribute("headertext", "<h1> Text</h1>");
return "index";
}
}
Index.jsp
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>th:utext</title>
</head>
<body>
<span th:text="${headertext}"/>
<p th:utext="${headertext}"></p>
<p th:utext="${'th:remove=all'+headertext}" th:remove="all"></p>
<p th:utext="${'th:remove=body'+headertext}" th:remove="body"></p>
<p th:utext="${'th:remove=tag'+headertext}" th:remove="tag"></p>
<p th:utext="${'th:remove=all-but-first'+headertext}" th:remove="all-but-first"></p>
<p th:utext="${'th:remove=none'+headertext}" th:remove="none"></p>
</body>
</html>