001/* 002 * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * bstefanescu 016 * 017 * $Id$ 018 */ 019 020package org.nuxeo.ecm.webengine.rendering; 021 022import java.io.IOException; 023import java.util.Map; 024 025import org.nuxeo.ecm.webengine.WebEngine; 026import org.nuxeo.ecm.webengine.model.WebContext; 027import org.nuxeo.ecm.webengine.model.impl.AbstractWebContext; 028import org.nuxeo.ecm.webengine.scripting.ScriptFile; 029 030import freemarker.core.Environment; 031import freemarker.template.SimpleScalar; 032import freemarker.template.Template; 033import freemarker.template.TemplateDirectiveBody; 034import freemarker.template.TemplateDirectiveModel; 035import freemarker.template.TemplateException; 036import freemarker.template.TemplateModel; 037import freemarker.template.TemplateModelException; 038 039/** 040 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 041 */ 042public class RenderDirective implements TemplateDirectiveModel { 043 044 public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) 045 throws TemplateException, IOException { 046 int size = params.size(); 047 if (size != 1) { 048 throw new TemplateModelException("Invalid number of arguments for render(...) method"); 049 } 050 051 SimpleScalar val = (SimpleScalar) params.get("src"); 052 if (val == null) { 053 throw new TemplateModelException("src attribute is required"); 054 } 055 String src = val.getAsString(); 056 057 WebContext ctx = WebEngine.getActiveContext(); 058 if (ctx != null) { 059 ScriptFile script = ctx.getFile(src); 060 Template tpl = env.getConfiguration().getTemplate(script.getURL()); 061 try { 062 ((AbstractWebContext) ctx).pushScriptFile(script.getFile()); 063 env.include(tpl); 064 } finally { 065 ((AbstractWebContext) ctx).popScriptFile(); 066 } 067 } else { 068 throw new IllegalStateException("Not In a Web Context"); 069 } 070 } 071 072}