We have a requirement to dynamically resolve html or text templates. The template content (a string) with variable place holders will be available in database.
We have to resolve them dynamically on demand with the actual values for the variables and get the final string content.
Example: (not a complete code)
String myHtmlTemplateContent = "<h1>Hi ${first_name} ${last_name}</h1>";
Map<String, Object> myMapWithValues = ..;
engine.resolve(myHtmlTemplateContent , myMapWithValues );
Will be helpful if we have a way to resolve using thymeleaf or is it possible using thymeleaf template engine.
You need to create a thymeleaf template mytemplate.html containing:
<h1 th:text="Hi ${first_name} ${last_name}"></h1>
and use it with a mvc controller that sets the variables in the model:
@Controller
public class HelloController {
@GetMapping("/hello")
public String handle(Model model) {
model.addAttribute("first_name", "Abel");
model.addAttribute("last_name", "Lincon");
return "mytemplate"; //resolves to mytemplate.html
}
}
And it will render <h1>Hi Abel Lincon</h1>
If you want to manually process a template, you could autowire the template engine and use it manually:
@Autowired SpringTemplateEngine templateEngine;
String emailContent = templateEngine.process( "mytemplate",
new Context( Locale.ENGLISH, Map.of(
"first_name", "Abel",
"last_name", "Lincon"
)) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With