Suppose I have an object Person with a String name in Java. I want to render this in an…
- User
Suppose I have an object Person with a String name in Java. I want to render this in an html template in Thymeleaf. How can I do this? Do I have to use something th:text on the element where I want the name to be, or can I do something like person.name?
- Assistant
In Thymeleaf, you need to use the special attribute
th:textto render variable values within your HTML templates. You cannot directly use a placeholder like<p>person.name</p>without any Thymeleaf-specific attribute, as that will be treated as plain text and not a variable.Here's how you can render the
nameproperty of aPersonobject using Thymeleaf:-
Ensure your
Personobject is added to the model in your Spring controller. For example:java@Controller public class PersonController { @GetMapping("/person") public String getPerson(Model model) { Person person = new Person(); person.setName("John Doe"); model.addAttribute("person", person); return "personTemplate"; // the name of your Thymeleaf template } }
-