I'm trying to render XML/JSON using Thymeleaf templates. I don't want to render a view using the template name, just want to resolve the template as shown below. Trouble is all I get back is the template name, not it's content.
Set up:
@Bean
SpringResourceTemplateResolver xmlTemplateResolver(ApplicationContext appCtx) {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(appCtx);
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".xml");
templateResolver.setTemplateMode(XML);
templateResolver.setCharacterEncoding(UTF_8.name());
templateResolver.setCacheable(false);
return templateResolver;
}
@Bean
SpringTemplateEngine templateEngine(ApplicationContext appCtx) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(xmlTemplateResolver(appCtx));
return templateEngine;
}
Template (src/main/resources/templates/breakfast-menu.xml):
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>${item['name']}</name>
<price>${item['price']}</price>
<description>${item['description']}</description>
<calories>${item['calories']}</calories>
</food>
</breakfast_menu>
Usage:
@Autowired
SpringTemplateEngine templateEngine;
someMethod() {
Context context = new Context();
context.setVariable("item", item);
item.put("name", "Waffle");
String content = templateEngine.process("breakfast-menu", context);
// content == "breakfast-menu". WTH?
}
Using Thymeleaf 3.0.0.BETA01.
I solved this issue with help from the Thymeleaf user forum. For reasons unbeknownst to me, templateEngine.addTemplateResolver
doesn't work but templateEngine.setTemplateResolver
does. The templates for XML and JSON output are shown below:
XML:
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name th:text="${item['name']}"></name>
<price th:text="${item['price']}"></price>
<description th:text="${item['description']}"></description>
<calories th:text="${item['calories']}"></calories>
</food>
</breakfast_menu>
JSON:
{
"food": {
"name": "[[${item['name']}]]",
"price": "[[${item['price']}]]",
"description": "[[${item['description']}]]",
"calories": "[[${item['calories']}]]"
}
}
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