01: /* ***** BEGIN LICENSE BLOCK *****
02: * Version: MPL 1.1
03: * The contents of this file are subject to the Mozilla Public License Version
04: * 1.1 (the "License"); you may not use this file except in compliance with
05: * the License. You may obtain a copy of the License at
06: * http://www.mozilla.org/MPL/
07: *
08: * Software distributed under the License is distributed on an "AS IS" basis,
09: * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10: * for the specific language governing rights and limitations under the
11: * License.
12: *
13: * The Original Code is Riot.
14: *
15: * The Initial Developer of the Original Code is
16: * Neteye GmbH.
17: * Portions created by the Initial Developer are Copyright (C) 2006
18: * the Initial Developer. All Rights Reserved.
19: *
20: * Contributor(s):
21: * Felix Gnass [fgnass at neteye dot de]
22: *
23: * ***** END LICENSE BLOCK ***** */
24: package org.riotfamily.forms;
25:
26: import java.io.PrintWriter;
27: import java.io.StringWriter;
28: import java.util.Collections;
29: import java.util.HashMap;
30: import java.util.Map;
31:
32: public class TemplateUtils {
33:
34: public static String getTemplatePath(Object object) {
35: return getTemplatePath(object, null);
36: }
37:
38: public static String getTemplatePath(Class clazz) {
39: return getTemplatePath(clazz, null);
40: }
41:
42: public static String getTemplatePath(Object object, String suffix) {
43: return getTemplatePath(object.getClass(), suffix);
44: }
45:
46: public static String getTemplatePath(Class clazz, String suffix) {
47: StringBuffer sb = new StringBuffer();
48: sb.append("classpath:/");
49: sb.append(clazz.getName().replace('.', '/'));
50: if (suffix != null) {
51: sb.append(suffix);
52: }
53: sb.append(".ftl");
54: return sb.toString();
55: }
56:
57: public static void render(FormContext context, String template,
58: String modelKey, Object object, PrintWriter writer) {
59:
60: HashMap model = new HashMap();
61: model.put(modelKey, object);
62: context.getTemplateRenderer().render(template, model, writer);
63: }
64:
65: public static String getInitScript(Element element) {
66: return getInitScript(element, element.getClass());
67: }
68:
69: public static String getInitScript(Element element, Class baseClass) {
70: StringWriter sw = new StringWriter();
71: PrintWriter writer = new PrintWriter(sw);
72:
73: FormContext context = element.getForm().getFormContext();
74: String template = getTemplatePath(baseClass, "_init");
75: Map model = Collections.singletonMap("element", element);
76: context.getTemplateRenderer().render(template, model, writer);
77:
78: return sw.toString();
79: }
80:
81: }
|