I want my own template loader for FreemarkerServlet. So I need to override "factory creation" method. I've attached a diff for this.
How to use it:
1) extend FreemarkerServlet:
-----------------------------------------------
public class CMSFreemarkerServlet extends FreemarkerServlet {
protected void processTemplatePath(String templatePath) throws IOException {
if (templatePath.startsWith("custom")) {
Configuration cfg = getConfiguration();
cfg.setTemplateLoader(new CMSSnippetLoader());
}
else {
super.processTemplatePath(templatePath);
}
}
class CMSSnippetLoader implements TemplateLoader {
public Object findTemplateSource(String name) throws IOException {
// HERE YOU CAN LOAD YOUR TEMPLATE
String snippetName = name.replace(".snippet", "");
return findSnippetByName(snippetName);
}
public long getLastModified(Object templateSource) {
return System.currentTimeMillis();
}
public Reader getReader(Object templateSource, String encoding) throws IOException {
return new StringReader(((Snippet)templateSource).getValue());
}
public void closeTemplateSource(Object templateSource) throws IOException {
}
}
}
---------------------------------------
2) in web.xml:
---------------------------------------
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>CMSFreemarkerServlet</servlet-class>
<!-- FreemarkerServlet settings: -->
<init-param>
<param-name>TemplatePath</param-name>
<param-value>custom</param-value>
</init-param>
<!-- other stuff -->
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.snippet</url-pattern>
</servlet-mapping>
-------------------------------------
3) Now you can include snippet:
-------------------------------------
RequestDispatcher disp = request.getRequestDispatcher("coolsnippet.snippet");
disp.include(request, response);
-------------------------------------
patch for freemarker 2.3.11
Logged In: YES
user_id=52489
Originator: NO
I've looked at your patch, but I rather opted for adding a "TemplateLoader createTemplateLoader()" method instead, as it conveys the intent more clearly.
Logged In: NO
it's up to you how to name methods :)
i'd just like to see this patch in next freemarker version, 'cause I use the patch in my cms
Logged In: YES
user_id=546667
Originator: NO
Fix released with 2.3.13.