Easier way to process against a string as template?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Easier way to process against a string as template?

Antibrumm
Hi all

I'm wondering if there is an easier way of running TemplateEngine.process(..) against a String parameter.

For an Email feature for a client I have implemented an entity which is persistet inside a database, so the client is able to define the notification templates at runtime as he desires.

This all works fine BUT probably there is a simpler solution then my current implementation?

Here's what I did to resolve a dynamic template:
- Create a second (Spring) TemplateEngine
- Register a MailTemplateResolver for the TemplateEngine
- Register a MailTemplateResourceResolver for the MailTemplate Resolver

The MailTemplateResourceResolver uses a ThreadLocal<String> containing the dynamic Template loaded from the database and provides a setter and a remove method for it.

Now the calling code looks like this:
	public String renderNotification(int templateId) {
		String templateString = loadTemplate();
		Context context = prepareContext();
		try {
			mailTemplateResourceResolver.setCurrentTemplate(templateString);
			return mailTemplateEngine.process("NotUsed", context);
		} catch (Exception ex) {
			log.error("Error", ex); //$NON-NLS-1$
		} finally {
			mailTemplateResourceResolver.clearTemplate();
		}
	}

Now there is not that much overhead.
As you can see the Resolver is basically useless, so I hope it could be done simpler :) Do I miss something? Ideally by just calling process(string, context);

Anyone got an idea?
Reply | Threaded
Open this post in threaded view
|

Re: Easier way to process against a string as template?

Zemi
Administrator
Hello,

no, you're not missing anything. The code could be simpler or more complex for different particular needs, but this is the idea.

We really do something similar in the Interactive Tutorial, see
   https://github.com/thymeleaf/thymeleaf-itutorial/blob/2.1-master/src/main/java/org/thymeleaf/tools/memoryexecutor/StaticTemplateExecutor.java

Regards,
   Zemi

Reply | Threaded
Open this post in threaded view
|

Re: Easier way to process against a string as template?

Antibrumm
Thanks Zemi

So nothing to do then on my side :)

Nice work with that itutorials page, btw, didn't know this one!