Dashboard > FreeMarker > Home > How to output a Reader object's contents into the template
FreeMarker Log In | Sign Up   View a printable version of the current page.
How to output a Reader object's contents into the template
Added by Attila Szegedi, last edited by Dániel Dékány on Okt 31, 2006

Assume you have a java.io.Reader object in the template model, and you wish to output its contents into the template output. You will have to create a special transform model:

package com.mycompany.whatever;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Map;

import freemarker.template.AdapterTemplateModel;
import freemarker.template.TemplateTransformModel;

public class ReaderDumper implements TemplateTransformModel {
    public Writer getWriter(Writer out, Map args) throws IOException {
        AdapterTemplateModel adapter = (AdapterTemplateModel)args.get("reader");
        Reader r = (Reader) adapter.getAdaptedObject(java.lang.Object.class);
        for (;;) {
            int c = r.read();
            if (c == -1) {
                break;
            }
            out.write(c);
        }
        return null;
    }
}

Next, you'll need to put an instance of it into your data model (or Configuration shared variables):

configuration.setSharedVariable("readerDumper", new ReaderDumper());

Then from the template, you can use

<@readerDumper reader=myReader />

To output the reader's contents into the template (assuming the "myReader" variable holds your java.io.Reader).

Alternatively, you can use the "?new" built-in to create the reader dumper without having to set up anything in your data model or Configuration:

<#assign readerDumper="com.mycompany.whatever.ReaderDumper"?new />
Site powered by a free Open Source Project / Non-profit License (more) of Confluence - the Enterprise wiki.
Learn more or evaluate Confluence for your organisation.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 1.4.2 Build:#214 Jun 30, 2005) - Bug/feature request - Contact Administrators