001/*
002 * (C) Copyright 2006-2011 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.platform.rendering.fm.extensions;
023
024import java.io.IOException;
025import java.util.Map;
026
027import freemarker.core.Environment;
028import freemarker.template.SimpleScalar;
029import freemarker.template.Template;
030import freemarker.template.TemplateDirectiveBody;
031import freemarker.template.TemplateDirectiveModel;
032import freemarker.template.TemplateException;
033import freemarker.template.TemplateModel;
034import freemarker.template.TemplateModelException;
035
036/**
037 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
038 */
039public class ExtendsDirective implements TemplateDirectiveModel {
040
041    @Override
042    @SuppressWarnings("rawtypes")
043    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
044            throws TemplateException, IOException {
045
046        if (body == null) {
047            throw new TemplateModelException("Expecting a body");
048        }
049
050        String src = null;
051        SimpleScalar scalar = (SimpleScalar) params.get("src");
052        if (scalar != null) {
053            src = scalar.getAsString();
054        } else {
055            throw new TemplateModelException("src attribute is not defined");
056        }
057
058        BlockWriter writer = (BlockWriter) env.getOut();
059        writer.suppressOutput = true;
060        body.render(writer);
061        writer.suppressOutput = false;
062
063        // now we should go into the base template and render it
064        // String oldPath = writer.reg.path;
065        // writer.reg.path = src;
066        Template temp = env.getConfiguration().getTemplate(src);
067        env.include(temp);
068        // writer.reg.path = oldPath;
069    }
070
071}