2 * Sone - TemplatePart.java - Copyright © 2010 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.text;
20 import java.io.IOException;
21 import java.io.StringWriter;
22 import java.io.Writer;
24 import net.pterodactylus.util.template.Template;
25 import net.pterodactylus.util.template.TemplateContext;
26 import net.pterodactylus.util.template.TemplateContextFactory;
27 import net.pterodactylus.util.template.TemplateException;
30 * {@link Part} implementation that is rendered using a {@link Template}.
32 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
34 public class TemplatePart implements Part, net.pterodactylus.util.template.Part {
36 /** The template context factory. */
37 private final TemplateContextFactory templateContextFactory;
39 /** The template to render for this part. */
40 private final Template template;
43 * Creates a new template part.
45 * @param templateContextFactory
46 * The template context factory
48 * The template to render
50 public TemplatePart(TemplateContextFactory templateContextFactory, Template template) {
51 this.templateContextFactory = templateContextFactory;
52 this.template = template;
60 * Sets a variable in the template.
63 * The key of the variable
65 * The value of the variable
66 * @return This template part (for method chaining)
68 public TemplatePart set(String key, Object value) {
69 template.getInitialContext().set(key, value);
81 public void render(Writer writer) throws IOException {
82 template.render(templateContextFactory.createTemplateContext().mergeContext(template.getInitialContext()), writer);
89 public void render(TemplateContext templateContext, Writer writer) throws TemplateException {
90 template.render(templateContext.mergeContext(template.getInitialContext()), writer);
101 public String toString() {
102 StringWriter stringWriter = new StringWriter();
104 render(stringWriter);
105 } catch (IOException ioe1) {
106 /* should never throw, ignore. */
108 return stringWriter.toString();