Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically resolve Thymeleaf templates

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.

like image 216
Abhijit Sarkar Avatar asked Jan 11 '16 22:01

Abhijit Sarkar


1 Answers

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']}]]"
  } 
}
like image 70
Abhijit Sarkar Avatar answered Oct 06 '22 11:10

Abhijit Sarkar