001/*
002 * Copyright 2002-2020 the original author or authors.
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 *      https://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
017package org.springframework.ui.freemarker;
018
019import java.io.IOException;
020import java.io.StringWriter;
021
022import freemarker.template.Template;
023import freemarker.template.TemplateException;
024
025/**
026 * Utility class for working with FreeMarker.
027 * Provides convenience methods to process a FreeMarker template with a model.
028 *
029 * @author Juergen Hoeller
030 * @since 14.03.2004
031 */
032public abstract class FreeMarkerTemplateUtils {
033
034        /**
035         * Process the specified FreeMarker template with the given model and write
036         * the result to the given Writer.
037         * <p>When using this method to prepare a text for a mail to be sent with Spring's
038         * mail support, consider wrapping IO/TemplateException in MailPreparationException.
039         * @param model the model object, typically a Map that contains model names
040         * as keys and model objects as values
041         * @return the result as String
042         * @throws IOException if the template wasn't found or couldn't be read
043         * @throws freemarker.template.TemplateException if rendering failed
044         * @see org.springframework.mail.MailPreparationException
045         */
046        public static String processTemplateIntoString(Template template, Object model)
047                        throws IOException, TemplateException {
048
049                StringWriter result = new StringWriter(1024);
050                template.process(model, result);
051                return result.toString();
052        }
053
054}