1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.struts2.components.template;
19
20 import java.util.HashMap;
21 import java.util.Map;
22
23 import org.apache.struts2.config.Settings;
24
25 /***
26 * The TemplateEngineManager will return a template engine for the template
27 */
28 public class TemplateEngineManager {
29 public static final String DEFAULT_TEMPLATE_TYPE_CONFIG_KEY = "struts.ui.templateSuffix";
30
31 private static final TemplateEngineManager MANAGER = new TemplateEngineManager();
32
33 /*** The default template extenstion is <code>ftl</code>. */
34 public static final String DEFAULT_TEMPLATE_TYPE = "ftl";
35
36 Map templateEngines = new HashMap();
37
38 private TemplateEngineManager() {
39 templateEngines.put("ftl", new FreemarkerTemplateEngine());
40 templateEngines.put("vm", new VelocityTemplateEngine());
41 templateEngines.put("jsp", new JspTemplateEngine());
42 }
43
44 /***
45 * Registers the given template engine.
46 * <p/>
47 * Will add the engine to the existing list of known engines.
48 * @param templateExtension filename extension (eg. .jsp, .ftl, .vm).
49 * @param templateEngine the engine.
50 */
51 public static void registerTemplateEngine(String templateExtension, TemplateEngine templateEngine) {
52 MANAGER.templateEngines.put(templateExtension, templateEngine);
53 }
54
55 /***
56 * Gets the TemplateEngine for the template name. If the template name has an extension (for instance foo.jsp), then
57 * this extension will be used to look up the appropriate TemplateEngine. If it does not have an extension, it will
58 * look for a Configuration setting "struts.ui.templateSuffix" for the extension, and if that is not set, it
59 * will fall back to "ftl" as the default.
60 *
61 * @param template Template used to determine which TemplateEngine to return
62 * @param templateTypeOverride Overrides the default template type
63 * @return the engine.
64 */
65 public static TemplateEngine getTemplateEngine(Template template, String templateTypeOverride) {
66 String templateType = DEFAULT_TEMPLATE_TYPE;
67 String templateName = template.toString();
68 if (templateName.indexOf(".") > 0) {
69 templateType = templateName.substring(templateName.indexOf(".") + 1);
70 } else if (templateTypeOverride !=null && templateTypeOverride.length() > 0) {
71 templateType = templateTypeOverride;
72 } else if (Settings.isSet(DEFAULT_TEMPLATE_TYPE_CONFIG_KEY)) {
73 templateType = (String) Settings.get(DEFAULT_TEMPLATE_TYPE_CONFIG_KEY);
74 }
75 return (TemplateEngine) MANAGER.templateEngines.get(templateType);
76 }
77
78
79 }