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    @Override
047    public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
048            TemplateDirectiveBody body) throws TemplateException, IOException {
049        int size = params.size();
050        if (size != 1) {
051            throw new TemplateModelException("Invalid number of arguments for render(...) method");
052        }
053
054        SimpleScalar val = (SimpleScalar) params.get("src");
055        if (val == null) {
056            throw new TemplateModelException("src attribute is required");
057        }
058        String src = val.getAsString();
059
060        WebContext ctx = WebEngine.getActiveContext();
061        if (ctx != null) {
062            ScriptFile script = ctx.getFile(src);
063            Template tpl = env.getConfiguration().getTemplate(script.getURL());
064            try {
065                ((AbstractWebContext) ctx).pushScriptFile(script.getFile());
066                env.include(tpl);
067            } finally {
068                ((AbstractWebContext) ctx).popScriptFile();
069            }
070        } else {
071            throw new IllegalStateException("Not In a Web Context");
072        }
073    }
074
075}