Menu

#198 Custom template loader in Freemarker Servlet

closed-fixed
5
2008-05-08
2008-02-13
Anonymous
No

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);
-------------------------------------

Discussion

  • Nobody/Anonymous

    patch for freemarker 2.3.11

     
  • Attila Szegedi

    Attila Szegedi - 2008-03-04

    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.

     
  • Attila Szegedi

    Attila Szegedi - 2008-03-04
    • assigned_to: nobody --> szegedia
    • status: open --> open-fixed
     
  • Nobody/Anonymous

    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

     
  • Dániel Dékány

    • status: open-fixed --> closed-fixed
     
  • Dániel Dékány

    Logged In: YES
    user_id=546667
    Originator: NO

    Fix released with 2.3.13.

     

Log in to post a comment.

MongoDB Logo MongoDB