The TemplateTransformModel
allows FM-Classic templates to
perform text transformations on any portion of a template. The signature
of a TemplateTransformModel is below:
public void transform(Reader source, PrintWriter output) throws IOException, TemplateModelException;
The two arguments in the method define the input and output for the transformation. Unlike other model interfaces, this method does not return a TemplateModel.
For situations where it is more convenient to write to a Writer
instead of a PrintWriter
, TemplateTransformModel2
can be used. This avoids having to perform redundant wrapping and unwrapping
of Writers
into PrintWriters
.
TemplateTransformModel2
provides the following signature:
public void transform(Reader source, Writer output) throws IOException, TemplateModelException;
The interface allows both input and output to be arbitrarily long. Implementing classes may want to perform buffering on the input to maximize speed. The input and output may also be adapted to suit other systems, such as an XML parser or XSL transformation engine.
If transformation does not exist, or the isEmpty()
method of
a transform model returns true, the transformation will not be called.
Instead, the template will be processed without transformation.
Sometimes you want to be able to pass parameters into a transformation, as well as the data to be transformed. A good way to do this is to use a method model to act as a parameterized factory method that returns a transform model.
For instance, if you wanted to perform a transformation into either
HTML or XML, depending on a variable, you could create a
TemplateMethodModel
that looks something like this:
public class TransformFactory implements TemplateMethodModel { ... public void exec(List arguments) throws TemplateModelException { // Get the type of transformation from the parameter list String transform = (String)arguments.get(0); String type = (String)arguments.get(1); String size = (String)arguments.get(2); // Send the parameters to the transformation model. if( transform.equals( "html" )) { return new HtmlTransform( type, size ); } else if( transform.equals( "xml" )) { return new XmlTransform( type, size ); } ... } ... }
The HtmlTransform and XmlTransform classes would implement
TemplateTransformModel
like this:
public class HtmlTransform implements TemplateTransformModel { public HtmlTransform( String name, String size ) { ... } ... public void transform(Reader source, PrintWriter output) throws TemplateModelException { // Transform markup using the type and size parameters ... } } ... }
You call the parameterized transformation the same way you would call a regular method model:
<transform markupTransform( "html", model.type, model.size )> ... (markup to be transformed) ... </transform>
Previous: Method Model | Next: Object Model |