Menu

Creating custom template cache

2019-04-04
2019-04-05
  • Keith Roberts

    Keith Roberts - 2019-04-04

    I've got a problem with FreeMarker veresion 2.3.28 caching that I'm not sure how to solve. I'm using FreeMarker in a Springboot service that stores FreeMarker templates in a database. The problem that I have is that each message in the database supports up to 3 fields that can be processed with FreeMarker. The current FreeMarker code appears to assume one content string for each call to the loader which will insert 1 piece of content into the cache.

    I would like to return a message source that contains a map; where the key in the map identifies the field and the value is the content to be processed. It looks to me like I will need to write my own custom TemplateCache. I've seen hints in some posts that indicate this can be done; but I don't see a method for setting the TemplateCache. Looks to me like I would need to make a complete copy of the FreeMarker configuration and a complete copy of the TemplateCache code to do this.

    Could call the db 3 times, one for each field; but that seems very inefficient.

     
  • Dániel Dékány

    The template loading that you can access through Configuration is quite opinioned, and not as flexible as it could be. Though if I understand well, at least ideally you want to load a Map of Template-s at once, as opposed to a single Template, which would be quite a stretch for any design.

    One approach to consider is simply not using the template loadre API-s like Configuration.getTemplate (and then of course TemplateCache is not relevant either). You can create Template-s with its consturctor directly, and then how they are loaded and cached is entierly up to you. The catch is that #include/ #import(and some more) still will try to load the template with Configuration.getTemplate. Luckiliy in many uses cases for those tempaltes that you want to #include/#import that can be good enough, and the special requirements tend to fall on loading/caching the top-level templates.

    Last not least, before you start creating your own mechanism, consider if simply loading the 3 tempaltes separately is a real performance issue in your application. How long will they stay cached, and how frequent up-of-date checks will be.

     

    Last edit: Dániel Dékány 2019-04-05

Log in to post a comment.