0

In my application I need to use "hardwired" html templates which I will bake in by adding them to resources/templates and "dynamic" text templates that I want to store in Strings at runtime.

My code looks similar to this:

@Autowired
SpringTemplateEngine templateEngine;

templateEngine.addTemplateResolver(new DynamicTemplateResolver());

Context context = new Context();
context.setVariable("foo1", ... );

templateEngine.process("eitherStaticOrDynamic", context, output);

The problem lies within DynamicTemplateResolver which implements ITemplateResolver. I tried to use the examples given at Process string templates with thymeleaf 3, but they seem to no longer work on current versions of Spring.

How can I resolve a template from Strings ? I use Spring Boot 2.2

Marged
  • 10,577
  • 10
  • 57
  • 99

1 Answers1

0

I guess I found the solution. My mistake was based on a misunderstanding. Thymeleaf provides a StringTemplateResolver with this javadoc:

... This template resolvers will consider the template being resolved as the template itself, this is, its contents. No external file or resource will be therefore accessed. ...

Hidden (at least to me) in this comment is the fact that instead of searching for a templates name the given string is considered a template. That means if you provide foo = [(${foo})] this is not considered as a template that needs to be looked up by name but instead treated as a (in this case: text) template !

This and changing my code to this solved the issue for me:

StringTemplateResolver tr = new StringTemplateResolver();
tr.setTemplateMode(TemplateMode.TEXT);

Without this setting my template was not resolved because text mode templates follow a different syntax than html templates.

Marged
  • 10,577
  • 10
  • 57
  • 99