001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.platform.rendering.fm.extensions;
016
017import java.io.IOException;
018import java.util.Map;
019
020import freemarker.core.Environment;
021import freemarker.template.SimpleScalar;
022import freemarker.template.TemplateDirectiveBody;
023import freemarker.template.TemplateDirectiveModel;
024import freemarker.template.TemplateException;
025import freemarker.template.TemplateModel;
026
027/**
028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
029 */
030public class BlockDirective implements TemplateDirectiveModel {
031
032    @Override
033    @SuppressWarnings("rawtypes")
034    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
035            throws TemplateException, IOException {
036
037        String name = null;
038        SimpleScalar scalar = (SimpleScalar) params.get("name");
039        if (scalar != null) {
040            name = scalar.getAsString();
041        }
042
043        scalar = (SimpleScalar) params.get("ifBlockDefined");
044        String ifBlockDefined = null;
045        if (scalar != null) {
046            ifBlockDefined = scalar.getAsString();
047        }
048
049        String page = env.getTemplate().getName();
050        BlockWriter writer = (BlockWriter) env.getOut();
051        BlockWriterRegistry reg = writer.getRegistry();
052        BlockWriter bw = new BlockWriter(page, name, reg);
053        bw.ifBlockDefined = ifBlockDefined;
054        writer.writeBlock(bw);
055        // render this block
056        if (body != null) {
057            body.render(bw);
058        }
059    }
060
061}