001/*
002 * (C) Copyright 2006-2008 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.webengine.rendering;
023
024import java.io.IOException;
025import java.util.Map;
026
027import org.nuxeo.ecm.webengine.WebEngine;
028import org.nuxeo.ecm.webengine.model.WebContext;
029import org.nuxeo.ecm.webengine.model.impl.AbstractWebContext;
030import org.nuxeo.ecm.webengine.scripting.ScriptFile;
031
032import freemarker.core.Environment;
033import freemarker.template.SimpleScalar;
034import freemarker.template.Template;
035import freemarker.template.TemplateDirectiveBody;
036import freemarker.template.TemplateDirectiveModel;
037import freemarker.template.TemplateException;
038import freemarker.template.TemplateModel;
039import freemarker.template.TemplateModelException;
040
041/**
042 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
043 */
044public class RenderDirective implements TemplateDirectiveModel {
045
046    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
047            throws TemplateException, IOException {
048        int size = params.size();
049        if (size != 1) {
050            throw new TemplateModelException("Invalid number of arguments for render(...) method");
051        }
052
053        SimpleScalar val = (SimpleScalar) params.get("src");
054        if (val == null) {
055            throw new TemplateModelException("src attribute is required");
056        }
057        String src = val.getAsString();
058
059        WebContext ctx = WebEngine.getActiveContext();
060        if (ctx != null) {
061            ScriptFile script = ctx.getFile(src);
062            Template tpl = env.getConfiguration().getTemplate(script.getURL());
063            try {
064                ((AbstractWebContext) ctx).pushScriptFile(script.getFile());
065                env.include(tpl);
066            } finally {
067                ((AbstractWebContext) ctx).popScriptFile();
068            }
069        } else {
070            throw new IllegalStateException("Not In a Web Context");
071        }
072    }
073
074}