freemarker.template
Class Template

java.lang.Object
  extended by freemarker.core.Configurable
      extended by freemarker.template.Template

public class Template
extends Configurable

A core FreeMarker API that represents a compiled template. Typically, you will use a Configuration object to instantiate a template.

      Configuration cfg = new Configuration();
      ...
      Template myTemplate = cfg.getTemplate("myTemplate.html");
   

However, you can also construct a template directly by passing in to the appropriate constructor a java.io.Reader instance that is set to read the raw template text. The compiled template is stored in an an efficient data structure for later use.

To render the template, i.e. to merge it with a data model, and thus produce "cooked" output, call the process method.

Any error messages from exceptions thrown during compilation will be included in the output stream and thrown back to the calling code. To change this behavior, you can install custom exception handlers using Configurable.setTemplateExceptionHandler(TemplateExceptionHandler) on a Configuration object (for all templates belonging to a configuration) or on a Template object (for a single template).

It's not legal to modify the values of FreeMarker settings: a) while the template is executing; b) if the template object is already accessible from multiple threads.

Version:
$Id: Template.java,v 1.216.2.3 2006/03/10 17:49:02 revusky Exp $

Nested Class Summary
static class Template.WrongEncodingException
           
 
Nested classes/interfaces inherited from class freemarker.core.Configurable
Configurable.UnknownSettingException
 
Field Summary
static java.lang.String DEFAULT_NAMESPACE_PREFIX
           
static java.lang.String NO_NS_PREFIX
           
 
Fields inherited from class freemarker.core.Configurable
ARITHMETIC_ENGINE_KEY, BOOLEAN_FORMAT_KEY, CLASSIC_COMPATIBLE_KEY, DATE_FORMAT_KEY, DATETIME_FORMAT_KEY, LOCALE_KEY, NUMBER_FORMAT_KEY, OBJECT_WRAPPER_KEY, OUTPUT_ENCODING_KEY, STRICT_BEAN_MODELS, TEMPLATE_EXCEPTION_HANDLER_KEY, TIME_FORMAT_KEY, TIME_ZONE_KEY, URL_ESCAPING_CHARSET_KEY
 
Constructor Summary
Template(java.lang.String name, java.io.Reader reader)
          Deprecated. This constructor uses the "default" Configuration instance, which can easily lead to erroneous, unpredictable behaviour. See more here....
Template(java.lang.String name, java.io.Reader reader, Configuration cfg)
          This is equivalent to Template(name, reader, cfg, null)
Template(java.lang.String name, java.io.Reader reader, Configuration cfg, java.lang.String encoding)
          Constructs a template from a character stream.
 
Method Summary
 void addImport(LibraryLoad ll)
          Called by code internally to maintain a list of imports
 void addMacro(Macro macro)
          Called by code internally to maintain a table of macros
 void addPrefixNSMapping(java.lang.String prefix, java.lang.String nsURI)
          This is used internally.
 javax.swing.tree.TreePath containingElements(int column, int line)
           
 Environment createProcessingEnvironment(java.lang.Object rootMap, java.io.Writer out)
          Same as createProcessingEnvironment(rootMap, out, null).
 Environment createProcessingEnvironment(java.lang.Object rootMap, java.io.Writer out, ObjectWrapper wrapper)
          Creates a Environment object, using this template, the data model provided as the root map object, and the supplied object wrapper to convert map elements to template models.
 void dump(java.io.PrintStream ps)
          Dump the raw template in canonical form.
 void dump(java.io.Writer out)
          Dump the raw template in canonical form.
 Configuration getConfiguration()
          Returns the Configuration object associated with this template.
 java.lang.String getDefaultNS()
           
 java.lang.String getEncoding()
          Returns the character encoding used for reading included files.
 java.util.List getImports()
           
 java.util.Map getMacros()
           
 java.lang.String getName()
          The path of the template file relative to the directory what you use to store the templates.
 java.lang.String getNamespaceForPrefix(java.lang.String prefix)
           
static Template getPlainTextTemplate(java.lang.String name, java.lang.String content, Configuration config)
          Returns a trivial template, one that is just a single block of plain text, no dynamic content.
 java.lang.String getPrefixedName(java.lang.String localName, java.lang.String nsURI)
           
 java.lang.String getPrefixForNamespace(java.lang.String nsURI)
           
 TemplateElement getRootTreeNode()
           
 java.lang.String getSource(int beginColumn, int beginLine, int endColumn, int endLine)
          Returns the template source at the location specified by the coordinates given.
 void process(java.lang.Object rootMap, java.io.Writer out)
          Processes the template, using data from the map, and outputs the resulting text to the supplied Writer The elements of the map are converted to template models using the default object wrapper returned by the getObjectWrapper() method of the Configuration.
 void process(java.lang.Object rootMap, java.io.Writer out, ObjectWrapper wrapper)
          Processes the template, using data from the root map object, and outputs the resulting text to the supplied writer, using the supplied object wrapper to convert map elements to template models.
 void process(java.lang.Object rootMap, java.io.Writer out, ObjectWrapper wrapper, TemplateNodeModel rootNode)
          Processes the template, using data from the root map object, and outputs the resulting text to the supplied writer, using the supplied object wrapper to convert map elements to template models.
 void setEncoding(java.lang.String encoding)
          Sets the character encoding to use for included files.
 java.lang.String toString()
          Returns a string representing the raw template text in canonical form.
 
Methods inherited from class freemarker.core.Configurable
clone, getArithmeticEngine, getBooleanFormat, getCustomAttribute, getCustomAttributeNames, getDateFormat, getDateTimeFormat, getEnvironment, getLocale, getNumberFormat, getObjectWrapper, getOutputEncoding, getParent, getSetting, getSettings, getTemplateExceptionHandler, getTimeFormat, getTimeZone, getURLEscapingCharset, invalidSettingValueException, isClassicCompatible, removeCustomAttribute, setArithmeticEngine, setBooleanFormat, setClassicCompatible, setCustomAttribute, setDateFormat, setDateTimeFormat, setLocale, setNumberFormat, setObjectWrapper, setOutputEncoding, setSetting, setSettings, setSettings, setStrictBeanModels, setTemplateExceptionHandler, setTimeFormat, setTimeZone, setURLEscapingCharset, unknownSettingException
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

DEFAULT_NAMESPACE_PREFIX

public static final java.lang.String DEFAULT_NAMESPACE_PREFIX
See Also:
Constant Field Values

NO_NS_PREFIX

public static final java.lang.String NO_NS_PREFIX
See Also:
Constant Field Values
Constructor Detail

Template

public Template(java.lang.String name,
                java.io.Reader reader,
                Configuration cfg,
                java.lang.String encoding)
         throws java.io.IOException
Constructs a template from a character stream.

Parameters:
name - the path of the template file relative to the directory what you use to store the templates. See getName() for more details.
reader - the character stream to read from. It will always be closed (Reader.close()).
cfg - the Configuration object that this Template is associated with. If this is null, the "default" Configuration object is used, which is highly discouraged, because it can easily lead to erroneous, unpredictable behaviour. (See more here...)
encoding - This is the encoding that we are supposed to be using. If this is non-null (It's not actually necessary because we are using a Reader) then it is checked against the encoding specified in the FTL header -- assuming that is specified, and if they don't match a WrongEncodingException is thrown.
Throws:
java.io.IOException

Template

public Template(java.lang.String name,
                java.io.Reader reader,
                Configuration cfg)
         throws java.io.IOException
This is equivalent to Template(name, reader, cfg, null)

Throws:
java.io.IOException

Template

public Template(java.lang.String name,
                java.io.Reader reader)
         throws java.io.IOException
Deprecated. This constructor uses the "default" Configuration instance, which can easily lead to erroneous, unpredictable behaviour. See more here....

Constructs a template from a character stream. This is the same as the 3 parameter version when you pass null as the cfg parameter.

Throws:
java.io.IOException
Method Detail

getPlainTextTemplate

public static Template getPlainTextTemplate(java.lang.String name,
                                            java.lang.String content,
                                            Configuration config)
Returns a trivial template, one that is just a single block of plain text, no dynamic content. (Used by the cache module to create unparsed templates.)

Parameters:
name - the path of the template file relative to the directory what you use to store the templates. See getName() for more details.
content - the block of text that this template represents
config - the configuration to which this template belongs

process

public void process(java.lang.Object rootMap,
                    java.io.Writer out)
             throws TemplateException,
                    java.io.IOException
Processes the template, using data from the map, and outputs the resulting text to the supplied Writer The elements of the map are converted to template models using the default object wrapper returned by the getObjectWrapper() method of the Configuration.

Parameters:
rootMap - the root node of the data model. If null, an empty data model is used. Can be any object that the effective object wrapper can turn into a TemplateHashModel. Basically, simple and beans wrapper can turn java.util.Map objects into hashes and the Jython wrapper can turn both a PyDictionary as well as any object that implements __getitem__ into a template hash. Naturally, you can pass any object directly implementing TemplateHashModel as well.
out - a Writer to output the text to.
Throws:
TemplateException - if an exception occurs during template processing
java.io.IOException - if an I/O exception occurs during writing to the writer.

process

public void process(java.lang.Object rootMap,
                    java.io.Writer out,
                    ObjectWrapper wrapper,
                    TemplateNodeModel rootNode)
             throws TemplateException,
                    java.io.IOException
Processes the template, using data from the root map object, and outputs the resulting text to the supplied writer, using the supplied object wrapper to convert map elements to template models.

Parameters:
rootMap - the root node of the data model. If null, an empty data model is used. Can be any object that the effective object wrapper can turn into a TemplateHashModel Basically, simple and beans wrapper can turn java.util.Map objects into hashes and the Jython wrapper can turn both a PyDictionary as well as any object that implements __getitem__ into a template hash. Naturally, you can pass any object directly implementing TemplateHashModel as well.
wrapper - The object wrapper to use to wrap objects into TemplateModel instances. If null, the default wrapper retrieved by Configurable.getObjectWrapper() is used.
out - the writer to output the text to.
rootNode - The root node for recursive processing, this may be null.
Throws:
TemplateException - if an exception occurs during template processing
java.io.IOException - if an I/O exception occurs during writing to the writer.

process

public void process(java.lang.Object rootMap,
                    java.io.Writer out,
                    ObjectWrapper wrapper)
             throws TemplateException,
                    java.io.IOException
Processes the template, using data from the root map object, and outputs the resulting text to the supplied writer, using the supplied object wrapper to convert map elements to template models.

Parameters:
rootMap - the root node of the data model. If null, an empty data model is used. Can be any object that the effective object wrapper can turn into a TemplateHashModel Basically, simple and beans wrapper can turn java.util.Map objects into hashes and the Jython wrapper can turn both a PyDictionary as well as any object that implements __getitem__ into a template hash. Naturally, you can pass any object directly implementing TemplateHashModel as well.
wrapper - The object wrapper to use to wrap objects into TemplateModel instances. If null, the default wrapper retrieved by Configurable.getObjectWrapper() is used.
out - the writer to output the text to.
Throws:
TemplateException - if an exception occurs during template processing
java.io.IOException - if an I/O exception occurs during writing to the writer.

createProcessingEnvironment

public Environment createProcessingEnvironment(java.lang.Object rootMap,
                                               java.io.Writer out,
                                               ObjectWrapper wrapper)
                                        throws TemplateException,
                                               java.io.IOException
Creates a Environment object, using this template, the data model provided as the root map object, and the supplied object wrapper to convert map elements to template models. You can then call Environment.process() on the returned environment to set off the actual rendering. Use this method if you want to do some special initialization on the environment before template processing, or if you want to read the environment after template processing.

Example:

This:

 Environment env = myTemplate.createProcessingEnvironment(root, out, null);
 env.process();
 
is equivalent with this:
 myTemplate.process(root, out);
 
But with createProcessingEnvironment, you can manipulate the environment before and after the processing:
 Environment env = myTemplate.createProcessingEnvironment(root, out);
 env.include("include/common.ftl", null, true);  // before processing
 env.process();
 TemplateModel x = env.getVariable("x");  // after processing
 

Parameters:
rootMap - the root node of the data model. If null, an empty data model is used. Can be any object that the effective object wrapper can turn into a TemplateHashModel Basically, simple and beans wrapper can turn java.util.Map objects into hashes and the Jython wrapper can turn both a PyDictionary as well as any object that implements __getitem__ into a template hash. Naturally, you can pass any object directly implementing TemplateHashModel as well.
wrapper - The object wrapper to use to wrap objects into TemplateModel instances. If null, the default wrapper retrieved by Configurable.getObjectWrapper() is used.
out - the writer to output the text to.
Returns:
the Environment object created for processing
Throws:
TemplateException - if an exception occurs while setting up the Environment object.
java.io.IOException - if an exception occurs doing any auto-imports

createProcessingEnvironment

public Environment createProcessingEnvironment(java.lang.Object rootMap,
                                               java.io.Writer out)
                                        throws TemplateException,
                                               java.io.IOException
Same as createProcessingEnvironment(rootMap, out, null).

Throws:
TemplateException
java.io.IOException
See Also:
createProcessingEnvironment(Object rootMap, Writer out, ObjectWrapper wrapper)

toString

public java.lang.String toString()
Returns a string representing the raw template text in canonical form.

Overrides:
toString in class java.lang.Object

getName

public java.lang.String getName()
The path of the template file relative to the directory what you use to store the templates. For example, if the real path of template is "/www/templates/community/forum.fm", and you use ""/www/templates" as "directoryForTemplateLoading", then name should be "community/forum.fm". The name is used for example when you use <include ...> and you give a path that is relative to the current template, or in error messages when FreeMarker logs an error while it processes the template.


getConfiguration

public Configuration getConfiguration()
Returns the Configuration object associated with this template.


setEncoding

public void setEncoding(java.lang.String encoding)
Sets the character encoding to use for included files. Usually you don't set this value manually, instead it is assigned to the template upon loading.


getEncoding

public java.lang.String getEncoding()
Returns the character encoding used for reading included files.


dump

public void dump(java.io.PrintStream ps)
Dump the raw template in canonical form.


dump

public void dump(java.io.Writer out)
          throws java.io.IOException
Dump the raw template in canonical form.

Throws:
java.io.IOException

addMacro

public void addMacro(Macro macro)
Called by code internally to maintain a table of macros


addImport

public void addImport(LibraryLoad ll)
Called by code internally to maintain a list of imports


getSource

public java.lang.String getSource(int beginColumn,
                                  int beginLine,
                                  int endColumn,
                                  int endLine)
Returns the template source at the location specified by the coordinates given.

Parameters:
beginColumn - the first column of the requested source, 1-based
beginLine - the first line of the requested source, 1-based
endColumn - the last column of the requested source, 1-based
endLine - the last line of the requested source, 1-based
See Also:
TemplateObject.getSource()

getRootTreeNode

public TemplateElement getRootTreeNode()
Returns:
the root TemplateElement object.

getMacros

public java.util.Map getMacros()

getImports

public java.util.List getImports()

addPrefixNSMapping

public void addPrefixNSMapping(java.lang.String prefix,
                               java.lang.String nsURI)
This is used internally.


getDefaultNS

public java.lang.String getDefaultNS()

getNamespaceForPrefix

public java.lang.String getNamespaceForPrefix(java.lang.String prefix)
Returns:
the NamespaceUri mapped to this prefix in this template. (Or null if there is none.)

getPrefixForNamespace

public java.lang.String getPrefixForNamespace(java.lang.String nsURI)
Returns:
the prefix mapped to this nsURI in this template. (Or null if there is none.)

getPrefixedName

public java.lang.String getPrefixedName(java.lang.String localName,
                                        java.lang.String nsURI)
Returns:
the prefixed name, based on the ns_prefixes defined in this template's header for the local name and node namespace passed in as parameters.

containingElements

public javax.swing.tree.TreePath containingElements(int column,
                                                    int line)
Parameters:
column - the column
line - the line
Returns:
an array of the elements containing the given column and line numbers.