public void renderTemplate(TemplateRenderingContext templateContext) throws Exception {
// get the various items required from the stack
ValueStack stack = templateContext.getStack();
Map context = stack.getContext();
ServletContext servletContext = (ServletContext) context.get(ServletActionContext.SERVLET_CONTEXT);
HttpServletRequest req = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse res = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
// prepare freemarker
Configuration config = freemarkerManager.getConfiguration(servletContext);
// get the list of templates we can use
List< Template > templates = templateContext.getTemplate().getPossibleTemplates(this);
// find the right template
freemarker.template.Template template = null;
String templateName = null;
Exception exception = null;
for (Template t : templates) {
templateName = getFinalTemplateName(t);
if (freemarkerCaching) {
if (!isTemplateMissing(templateName)) {
try {
template = findInCache(templateName); // look in cache first
if (template == null) {
// try to load, and if it works, stop at the first one
template = config.getTemplate(templateName);
addToCache(templateName, template);
}
break;
} catch (IOException e) {
addToMissingTemplateCache(templateName);
if (exception == null) {
exception = e;
}
}
}
} else {
try {
// try to load, and if it works, stop at the first one
template = config.getTemplate(templateName);
break;
} catch (IOException e) {
if (exception == null) {
exception = e;
}
}
}
}
if (template == null) {
LOG.error("Could not load template " + templateContext.getTemplate());
if (exception != null) {
throw exception;
} else {
return;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Rendering template " + templateName);
}
ActionInvocation ai = ActionContext.getContext().getActionInvocation();
Object action = (ai == null) ? null : ai.getAction();
SimpleHash model = freemarkerManager.buildTemplateModel(stack, action, servletContext, req, res, config.getObjectWrapper());
model.put("tag", templateContext.getTag());
model.put("themeProperties", getThemeProps(templateContext.getTemplate()));
// the BodyContent JSP writer doesn't like it when FM flushes automatically --
// so let's just not do it (it will be flushed eventually anyway)
Writer writer = templateContext.getWriter();
if (bodyContent != null && bodyContent.isAssignableFrom(writer.getClass())) {
final Writer wrapped = writer;
writer = new Writer() {
public void write(char cbuf[], int off, int len) throws IOException {
wrapped.write(cbuf, off, len);
}
public void flush() throws IOException {
// nothing!
}
public void close() throws IOException {
wrapped.close();
}
};
}
try {
stack.push(templateContext.getTag());
template.process(model, writer);
} finally {
stack.pop();
}
}
|