freemarker.template
Class Configuration

java.lang.Object
  extended by freemarker.core.Configurable
      extended by freemarker.template.Configuration
All Implemented Interfaces:
java.lang.Cloneable

public class Configuration
extends Configurable
implements java.lang.Cloneable

Main entry point into the FreeMarker API, this class encapsulates the various configuration parameters with which FreeMarker is run, as well as serves as a central template loading and caching point. Note that this class uses a default strategy for loading and caching templates. You can plug in a replacement template loading mechanism by using the setTemplateLoader(TemplateLoader) method. This object is not synchronized. Thus, the settings must not be changed after you have started to access the object from multiple threads. If you use multiple threads, set everything directly after you have instantiated the Configuration object, and don't change the settings anymore.

Version:
$Id: Configuration.java,v 1.122.2.5 2006/04/26 21:25:19 ddekany Exp $
Author:
Jonathan Revusky, Attila Szegedi

Nested Class Summary
 
Nested classes/interfaces inherited from class freemarker.core.Configurable
Configurable.UnknownSettingException
 
Field Summary
static int ANGLE_BRACKET_TAG_SYNTAX
           
static int AUTO_DETECT_TAG_SYNTAX
           
static java.lang.String AUTO_IMPORT_KEY
           
static java.lang.String AUTO_INCLUDE_KEY
           
static java.lang.String CACHE_STORAGE_KEY
           
static java.lang.String DEFAULT_ENCODING_KEY
           
static java.lang.String LOCALIZED_LOOKUP_KEY
           
static int SQUARE_BRACKET_TAG_SYNTAX
           
static java.lang.String STRICT_SYNTAX_KEY
           
static java.lang.String TAG_SYNTAX_KEY
           
static java.lang.String TEMPLATE_UPDATE_DELAY_KEY
           
static java.lang.String WHITESPACE_STRIPPING_KEY
           
 
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
Configuration()
           
 
Method Summary
 void addAutoImport(java.lang.String namespace, java.lang.String template)
          Add an auto-imported template.
 void addAutoInclude(java.lang.String templateName)
          add a template to be automatically included at the top of any template that is vended by this Configuration object.
 void clearEncodingMap()
          Clears language-to-encoding map.
 void clearSharedVariables()
          Removes all shared variables, except the predefined ones (compress, html_escape, etc.).
 void clearTemplateCache()
          Removes all entries from the template cache, thus forcing reloading of templates on subsequent getTemplate calls.
 java.lang.Object clone()
           
static Configuration getDefaultConfiguration()
          Deprecated. The usage of the static singleton (the "default") Configuration instance can easily cause erroneous, unpredictable behavior. This is because multiple independent software components may use FreeMarker internally inside the same application, so they will interfere because of the common Configuration instance. Each such component should use its own private Configuration object instead, that it typically creates with new Configuration() when the component is initialized.
 java.lang.String getDefaultEncoding()
          Gets the default encoding for converting bytes to characters when reading template files in a locale for which no explicit encoding was specified.
 java.lang.String getEncoding(java.util.Locale loc)
          Gets the preferred character encoding for the given locale, or the default encoding if no encoding is set explicitly for the specified locale.
 boolean getLocalizedLookup()
          Returns if localized template lookup is enabled or not.
 TemplateModel getSharedVariable(java.lang.String name)
          Gets a shared variable.
 java.util.Set getSharedVariableNames()
          Returns the set containing the names of all defined shared variables.
 boolean getStrictSyntaxMode()
          Tells whether directives such as if, else, etcetera must be written as #if, #else, etcetera.
 int getTagSyntax()
           
 Template getTemplate(java.lang.String name)
          Equivalent to getTemplate(name, thisCfg.getLocale(), thisCfg.getEncoding(thisCfg.getLocale()), true).
 Template getTemplate(java.lang.String name, java.util.Locale locale)
          Equivalent to getTemplate(name, locale, thisCfg.getEncoding(locale), true).
 Template getTemplate(java.lang.String name, java.util.Locale locale, java.lang.String encoding)
          Equivalent to getTemplate(name, locale, encoding, true).
 Template getTemplate(java.lang.String name, java.util.Locale locale, java.lang.String encoding, boolean parse)
          Retrieves a template specified by a name and locale, interpreted using the specified character encoding, either parsed or unparsed.
 Template getTemplate(java.lang.String name, java.lang.String encoding)
          Equivalent to getTemplate(name, thisCfg.getLocale(), encoding, true).
 TemplateLoader getTemplateLoader()
           
static java.lang.String getVersionNumber()
          Returns FreeMarker version number string.
 boolean getWhitespaceStripping()
          Gets whether the FTL parser will try to remove superfluous white-space around certain FTL tags.
 void loadBuiltInEncodingMap()
          Loads a preset language-to-encoding map.
 void removeAutoImport(java.lang.String namespace)
          Remove an auto-imported template
 void removeAutoInclude(java.lang.String templateName)
          remove a template from the auto-include list.
 void setAllSharedVariables(TemplateHashModelEx hash)
          Adds all object in the hash as shared variable to the configuration.
 void setAutoImports(java.util.Map map)
          set a map of namespace names to templates for auto-importing a set of templates.
 void setAutoIncludes(java.util.List templateNames)
          set the list of automatically included templates.
 void setCacheStorage(CacheStorage storage)
           
 void setClassForTemplateLoading(java.lang.Class clazz, java.lang.String pathPrefix)
          Sets a class relative to which we do the Class.getResource() call to load templates.
static void setDefaultConfiguration(Configuration config)
          Deprecated. Using the "default" Configuration instance can easily lead to erroneous, unpredictable behaviour. See more here....
 void setDefaultEncoding(java.lang.String encoding)
          Sets the default encoding for converting bytes to characters when reading template files in a locale for which no explicit encoding was specified.
 void setDirectoryForTemplateLoading(java.io.File dir)
          Set the explicit directory from which to load templates.
 void setEncoding(java.util.Locale locale, java.lang.String encoding)
          Sets the character set encoding to use for templates of a given locale.
 void setLocalizedLookup(boolean localizedLookup)
          Enables/disables localized template lookup.
 void setServletContextForTemplateLoading(java.lang.Object sctxt, java.lang.String path)
          Sets the servlet context from which to load templates
 void setSetting(java.lang.String key, java.lang.String value)
          Sets a setting by name and string value.
 void setSharedVariable(java.lang.String name, java.lang.Object obj)
          Adds shared variable to the configuration.
 void setSharedVariable(java.lang.String name, TemplateModel tm)
          Adds a shared variable to the configuration.
 void setStrictSyntaxMode(boolean b)
          Sets whether directives such as if, else, etcetera must be written as #if, #else, etcetera.
 void setTagSyntax(int tagSyntax)
          Determines the syntax of the template files (angle bracket VS square bracket) that has no ftl directive in it.
 void setTemplateLoader(TemplateLoader loader)
          Sets a template loader that is used to look up and load templates.
 void setTemplateUpdateDelay(int delay)
          Set the time in seconds that must elapse before checking whether there is a newer version of a template file.
 void setWhitespaceStripping(boolean b)
          Sets whether the FTL parser will try to remove superfluous white-space around certain FTL tags.
 
Methods inherited from class freemarker.core.Configurable
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, setSettings, setSettings, setStrictBeanModels, setTemplateExceptionHandler, setTimeFormat, setTimeZone, setURLEscapingCharset, unknownSettingException
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_ENCODING_KEY

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

LOCALIZED_LOOKUP_KEY

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

STRICT_SYNTAX_KEY

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

WHITESPACE_STRIPPING_KEY

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

CACHE_STORAGE_KEY

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

TEMPLATE_UPDATE_DELAY_KEY

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

AUTO_IMPORT_KEY

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

AUTO_INCLUDE_KEY

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

TAG_SYNTAX_KEY

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

AUTO_DETECT_TAG_SYNTAX

public static final int AUTO_DETECT_TAG_SYNTAX
See Also:
Constant Field Values

ANGLE_BRACKET_TAG_SYNTAX

public static final int ANGLE_BRACKET_TAG_SYNTAX
See Also:
Constant Field Values

SQUARE_BRACKET_TAG_SYNTAX

public static final int SQUARE_BRACKET_TAG_SYNTAX
See Also:
Constant Field Values
Constructor Detail

Configuration

public Configuration()
Method Detail

clone

public java.lang.Object clone()
Overrides:
clone in class Configurable

loadBuiltInEncodingMap

public void loadBuiltInEncodingMap()
Loads a preset language-to-encoding map. It assumes the usual character encodings for most languages. The previous content of the encoding map will be lost. This default map currently contains the following mappings:
arISO-8859-6
beISO-8859-5
bgISO-8859-5
caISO-8859-1
csISO-8859-2
daISO-8859-1
deISO-8859-1
elISO-8859-7
enISO-8859-1
esISO-8859-1
etISO-8859-1
fiISO-8859-1
frISO-8859-1
hrISO-8859-2
huISO-8859-2
isISO-8859-1
itISO-8859-1
iwISO-8859-8
jaShift_JIS
koEUC-KR
ltISO-8859-2
lvISO-8859-2
mkISO-8859-5
nlISO-8859-1
noISO-8859-1
plISO-8859-2
ptISO-8859-1
roISO-8859-2
ruISO-8859-5
shISO-8859-5
skISO-8859-2
slISO-8859-2
sqISO-8859-2
srISO-8859-5
svISO-8859-1
trISO-8859-9
ukISO-8859-5
zhGB2312
zh_TWBig5

See Also:
clearEncodingMap(), setEncoding(java.util.Locale, java.lang.String)

clearEncodingMap

public void clearEncodingMap()
Clears language-to-encoding map.

See Also:
loadBuiltInEncodingMap(), setEncoding(java.util.Locale, java.lang.String)

getDefaultConfiguration

public static Configuration getDefaultConfiguration()
Deprecated. The usage of the static singleton (the "default") Configuration instance can easily cause erroneous, unpredictable behavior. This is because multiple independent software components may use FreeMarker internally inside the same application, so they will interfere because of the common Configuration instance. Each such component should use its own private Configuration object instead, that it typically creates with new Configuration() when the component is initialized.

Returns the default (singleton) Configuration object. Note that you can create as many separate configurations as you wish; this global instance is provided for convenience, or when you have no reason to use a separate instance.


setDefaultConfiguration

public static void setDefaultConfiguration(Configuration config)
Deprecated. Using the "default" Configuration instance can easily lead to erroneous, unpredictable behaviour. See more here....

Sets the Configuration object that will be retrieved from future calls to getDefaultConfiguration().


setTemplateLoader

public void setTemplateLoader(TemplateLoader loader)
Sets a template loader that is used to look up and load templates. By providing your own template loader, you can customize the way templates are loaded. Several convenience methods in this class already allow you to install commonly used loaders: setClassForTemplateLoading(Class, String), setDirectoryForTemplateLoading(File), and setServletContextForTemplateLoading(Object, String). By default, a multi-loader is used that first tries to load a template from the file in the current directory, then from a resource on the classpath.


getTemplateLoader

public TemplateLoader getTemplateLoader()
Returns:
the template loader that is used to look up and load templates.
See Also:
setTemplateLoader(freemarker.cache.TemplateLoader)

setCacheStorage

public void setCacheStorage(CacheStorage storage)

setDirectoryForTemplateLoading

public void setDirectoryForTemplateLoading(java.io.File dir)
                                    throws java.io.IOException
Set the explicit directory from which to load templates.

Throws:
java.io.IOException

setServletContextForTemplateLoading

public void setServletContextForTemplateLoading(java.lang.Object sctxt,
                                                java.lang.String path)
Sets the servlet context from which to load templates

Parameters:
sctxt - the ServletContext object. Note that the type is Object to prevent class loading errors when user who uses FreeMarker not for servlets has no javax.servlet in the CLASSPATH.
path - the path relative to the ServletContext. If this path is absolute, it is taken to be relative to the server's URL, i.e. http://myserver.com/ and if the path is relative, it is taken to be relative to the web app context, i.e. http://myserver.context.com/mywebappcontext/

setClassForTemplateLoading

public void setClassForTemplateLoading(java.lang.Class clazz,
                                       java.lang.String pathPrefix)
Sets a class relative to which we do the Class.getResource() call to load templates.


setTemplateUpdateDelay

public void setTemplateUpdateDelay(int delay)
Set the time in seconds that must elapse before checking whether there is a newer version of a template file. This method is thread-safe and can be called while the engine works.


setStrictSyntaxMode

public void setStrictSyntaxMode(boolean b)
Sets whether directives such as if, else, etcetera must be written as #if, #else, etcetera. Any tag not starting with <# or </# is considered as plain text and will go to the output as is. Tag starting with <# or </# must be valid FTL tag, or else the template is invalid (i.e. <#noSuchDirective> is an error).


getStrictSyntaxMode

public boolean getStrictSyntaxMode()
Tells whether directives such as if, else, etcetera must be written as #if, #else, etcetera.

See Also:
setStrictSyntaxMode(boolean)

setWhitespaceStripping

public void setWhitespaceStripping(boolean b)
Sets whether the FTL parser will try to remove superfluous white-space around certain FTL tags.


getWhitespaceStripping

public boolean getWhitespaceStripping()
Gets whether the FTL parser will try to remove superfluous white-space around certain FTL tags.

See Also:
setWhitespaceStripping(boolean)

setTagSyntax

public void setTagSyntax(int tagSyntax)
Determines the syntax of the template files (angle bracket VS square bracket) that has no ftl directive in it. The tagSyntax parameter must be one of:

In FreeMarker 2.3.x ANGLE_BRACKET_TAG_SYNTAX is the default for better backward compatibility. Starting from 2.4.x AUTO_DETECT_TAG_SYNTAX is the default, so it is recommended to use that even for 2.3.x.

This setting is ignored for the templates that have ftl directive in it. For those templates the syntax used for the ftl directive determines the syntax.


getTagSyntax

public int getTagSyntax()
Returns:
whether the alternative square bracket syntax is set as the default

getTemplate

public Template getTemplate(java.lang.String name)
                     throws java.io.IOException
Equivalent to getTemplate(name, thisCfg.getLocale(), thisCfg.getEncoding(thisCfg.getLocale()), true).

Throws:
java.io.IOException

getTemplate

public Template getTemplate(java.lang.String name,
                            java.util.Locale locale)
                     throws java.io.IOException
Equivalent to getTemplate(name, locale, thisCfg.getEncoding(locale), true).

Throws:
java.io.IOException

getTemplate

public Template getTemplate(java.lang.String name,
                            java.lang.String encoding)
                     throws java.io.IOException
Equivalent to getTemplate(name, thisCfg.getLocale(), encoding, true).

Throws:
java.io.IOException

getTemplate

public Template getTemplate(java.lang.String name,
                            java.util.Locale locale,
                            java.lang.String encoding)
                     throws java.io.IOException
Equivalent to getTemplate(name, locale, encoding, true).

Throws:
java.io.IOException

getTemplate

public Template getTemplate(java.lang.String name,
                            java.util.Locale locale,
                            java.lang.String encoding,
                            boolean parse)
                     throws java.io.IOException
Retrieves a template specified by a name and locale, interpreted using the specified character encoding, either parsed or unparsed. For the exact semantics of parameters, see TemplateCache.getTemplate(String, Locale, String, boolean).

Returns:
the requested template.
Throws:
java.io.FileNotFoundException - if the template could not be found.
java.io.IOException - if there was a problem loading the template.
ParseException - (extends IOException) if the template is syntactically bad.

setDefaultEncoding

public void setDefaultEncoding(java.lang.String encoding)
Sets the default encoding for converting bytes to characters when reading template files in a locale for which no explicit encoding was specified. Defaults to default system encoding.


getDefaultEncoding

public java.lang.String getDefaultEncoding()
Gets the default encoding for converting bytes to characters when reading template files in a locale for which no explicit encoding was specified. Defaults to default system encoding.


getEncoding

public java.lang.String getEncoding(java.util.Locale loc)
Gets the preferred character encoding for the given locale, or the default encoding if no encoding is set explicitly for the specified locale. You can associate encodings with locales using setEncoding(Locale, String) or loadBuiltInEncodingMap().

Parameters:
loc - the locale
Returns:
the preferred character encoding for the locale.

setEncoding

public void setEncoding(java.util.Locale locale,
                        java.lang.String encoding)
Sets the character set encoding to use for templates of a given locale. If there is no explicit encoding set for some locale, then the default encoding will be used, what you can set with setDefaultEncoding(java.lang.String).

See Also:
clearEncodingMap(), loadBuiltInEncodingMap()

setSharedVariable

public void setSharedVariable(java.lang.String name,
                              TemplateModel tm)
Adds a shared variable to the configuration. Shared variables are variables that are visible as top-level variables for all templates which use this configuration, if the data model does not contain a variable with the same name.

Never use TemplateModel implementation that is not thread-safe for shared variables, if the configuration is used by multiple threads! It is the typical situation for Servlet based Web sites.

Parameters:
name - the name used to access the data object from your template. If a shared variable with this name already exists, it will replace that.
See Also:
setSharedVariable(String,Object), setAllSharedVariables(freemarker.template.TemplateHashModelEx)

getSharedVariableNames

public java.util.Set getSharedVariableNames()
Returns the set containing the names of all defined shared variables. The method returns a new Set object on each call that is completely disconnected from the Configuration. That is, modifying the set will have no effect on the Configuration object.


setSharedVariable

public void setSharedVariable(java.lang.String name,
                              java.lang.Object obj)
                       throws TemplateModelException
Adds shared variable to the configuration. It uses Configurable.getObjectWrapper() to wrap the obj.

Throws:
TemplateModelException
See Also:
setSharedVariable(String,TemplateModel), setAllSharedVariables(freemarker.template.TemplateHashModelEx)

setAllSharedVariables

public void setAllSharedVariables(TemplateHashModelEx hash)
                           throws TemplateModelException
Adds all object in the hash as shared variable to the configuration.

Never use TemplateModel implementation that is not thread-safe for shared variables, if the configuration is used by multiple threads! It is the typical situation for Servlet based Web sites.

Parameters:
hash - a hash model whose objects will be copied to the configuration with same names as they are given in the hash. If a shared variable with these names already exist, it will be replaced with those from the map.
Throws:
TemplateModelException
See Also:
setSharedVariable(String,Object), setSharedVariable(String,TemplateModel)

getSharedVariable

public TemplateModel getSharedVariable(java.lang.String name)
Gets a shared variable. Shared variables are variables that are available to all templates. When a template is processed, and an identifier is undefined in the data model, a shared variable object with the same identifier is then looked up in the configuration. There are several predefined variables that are always available through this method, see the FreeMarker manual for a comprehensive list of them.

See Also:
setSharedVariable(String,Object), setSharedVariable(String,TemplateModel), setAllSharedVariables(freemarker.template.TemplateHashModelEx)

clearSharedVariables

public void clearSharedVariables()
Removes all shared variables, except the predefined ones (compress, html_escape, etc.).


clearTemplateCache

public void clearTemplateCache()
Removes all entries from the template cache, thus forcing reloading of templates on subsequent getTemplate calls. This method is thread-safe and can be called while the engine works.


getLocalizedLookup

public boolean getLocalizedLookup()
Returns if localized template lookup is enabled or not. This method is thread-safe and can be called while the engine works.


setLocalizedLookup

public void setLocalizedLookup(boolean localizedLookup)
Enables/disables localized template lookup. Enabled by default. This method is thread-safe and can be called while the engine works.


setSetting

public void setSetting(java.lang.String key,
                       java.lang.String value)
                throws TemplateException
Sets a setting by name and string value. In additional to the settings understood by the super method, it understands these:

Overrides:
setSetting in class Configurable
Parameters:
key - the name of the setting.
value - the string that describes the new value of the setting.
Throws:
UnknownSettingException - if the key is wrong.
TemplateException - if the new value of the setting can't be set for any other reasons.

addAutoImport

public void addAutoImport(java.lang.String namespace,
                          java.lang.String template)
Add an auto-imported template. The importing will happen at the top of any template that is vended by this Configuration object.

Parameters:
namespace - the name of the namespace into which the template is imported
template - the name of the template

removeAutoImport

public void removeAutoImport(java.lang.String namespace)
Remove an auto-imported template

Parameters:
namespace - the name of the namespace into which the template was imported

setAutoImports

public void setAutoImports(java.util.Map map)
set a map of namespace names to templates for auto-importing a set of templates. Note that all previous auto-imports are removed.


addAutoInclude

public void addAutoInclude(java.lang.String templateName)
add a template to be automatically included at the top of any template that is vended by this Configuration object.

Parameters:
templateName - the lookup name of the template.

setAutoIncludes

public void setAutoIncludes(java.util.List templateNames)
set the list of automatically included templates. Note that all previous auto-includes are removed.


removeAutoInclude

public void removeAutoInclude(java.lang.String templateName)
remove a template from the auto-include list.

Parameters:
templateName - the lookup name of the template in question.

getVersionNumber

public static java.lang.String getVersionNumber()
Returns FreeMarker version number string. Examples of possible return values: "2.2.5", "2.3pre13", "2.3pre13mod", "2.3rc1", "2.3", "3.0".

Notes on FreeMarker version numbering rules: