com.mysema.commons.freemarker.ScriptDirective Maven / Gradle / Ivy
/*
* Copyright (c) 2009 Mysema Ltd.
* All rights reserved.
*
*/
package com.mysema.commons.freemarker;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.mysema.commons.fluxml.XMLWriter;
import freemarker.core.Environment;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
* MessageDirective GXP (Google XML Pages) like message localization
*
* @author tiwe
* @version $Id$
*/
public class ScriptDirective extends FreeMarkerHelper {
// TODO : take optional context extra parameter
private static final String STRING_WRITER_REQUEST_ATTRIBUTE = "@@scriptWriter@@";
@SuppressWarnings("unchecked")
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
XMLWriter out = new XMLWriter(env.getOut());
HttpServletRequest req = getRequest(env);
StringWriter writer = (StringWriter) req.getAttribute(STRING_WRITER_REQUEST_ATTRIBUTE);
if (writer == null) {
writer = new StringWriter();
}
if (body != null) {
body.render(writer);
}
TemplateBooleanModel flush = (TemplateBooleanModel) params.get("flush");
if (flush != null && flush.getAsBoolean()) {
out.begin("script");
out.attribute("type", "text/javascript");
out.printRaw(writer.getBuffer().toString());
out.end("script");
req.removeAttribute(STRING_WRITER_REQUEST_ATTRIBUTE);
} else {
req.setAttribute(STRING_WRITER_REQUEST_ATTRIBUTE, writer);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy