Package freemarker.template
Class Configuration
java.lang.Object
freemarker.core.Configurable
freemarker.template.Configuration
- All Implemented Interfaces:
Scope,TemplateHashModel,TemplateHashModelEx,TemplateModel,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.-
Nested Class Summary
Nested classes/interfaces inherited from class freemarker.core.Configurable
Configurable.UnknownSettingExceptionNested classes/interfaces inherited from interface freemarker.template.TemplateModel
TemplateModel.InvalidExpressionModel, TemplateModel.JavaNull -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intstatic final intstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final Stringstatic final intstatic final Stringstatic final Stringstatic final Stringstatic final StringFields inherited from class freemarker.core.Configurable
ARITHMETIC_ENGINE_KEY, BOOLEAN_FORMAT_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_KEYFields inherited from interface freemarker.template.TemplateModel
INVALID_EXPRESSION, JAVA_NULL, NOTHING -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddAutoImport(String namespace, String template) Add an auto-imported template.voidaddAutoInclude(String templateName) add a template to be automatically included at the top of any template that is vended by this Configuration object.voidaddAutoTemplateVisitors(freemarker.core.ast.ASTVisitor... visitors) voidClears language-to-encoding map.voidRemoves all shared variables, except the predefined ones (compress, html_escape, etc.).voidRemoves all entries from the template cache, thus forcing reloading of templates on subsequentgetTemplatecalls.clone()booleandefinesVariable(String name) protected voidbooleanWe're keeping this functionality for now, but if there is no sign anybody is interested in using this, it will likely be removed.booleanWe're keeping this functionality for now, but if there is no sign anybody is interested in using this, it will likely be removed.booleanWe're keeping this functionality for now, but if there is no sign anybody is interested in using this, it will likely be removed.Gets a TemplateModel from the hash.static Configurationstatic ObjectWrapperstatic ConfigurationDeprecated.Gets the default encoding for converting bytes to characters when reading template files in a locale for which no explicit encoding was specified.Returns the names of variables directly managed by this scope (i.e.getEncoding(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.booleanReturns if localized template lookup is enabled or not.getSharedVariable(String name) Gets a shared variable.Returns the set containing the names of all defined shared variables.booleanintgetTemplate(String name) Equivalent to getTemplate(name, thisCfg.getLocale(), thisCfg.getEncoding(thisCfg.getLocale()), true).getTemplate(String name, String encoding) Equivalent to getTemplate(name, thisCfg.getLocale(), encoding, true).getTemplate(String name, Locale locale) Equivalent to getTemplate(name, locale, thisCfg.getEncoding(locale), true).getTemplate(String name, Locale locale, String encoding) Equivalent to getTemplate(name, locale, encoding, true).getTemplate(String name, Locale locale, String encoding, boolean parse) Retrieves a template specified by a name and locale, interpreted using the specified character encoding, either parsed or unparsed.static StringReturns FreeMarker version.booleanGets whether the FTL parser will try to remove superfluous white-space around certain FTL tags.booleanisEmpty()booleanisSecure()keys()voidLoads a preset language-to-encoding map.voidput(String varname, TemplateModel value) Set a variable in this scope.Removes a variable in this scope.voidremoveAutoImport(String namespace) Remove an auto-imported templatevoidremoveAutoInclude(String templateName) remove a template from the auto-include list.voidremoveAutoTemplateVisitors(freemarker.core.ast.ASTVisitor... visitors) resolveVariable(String name) Evaluates the variable of this name in this scope, falling back to the enclosing Scope if it is not defined in this one.voidAdds all object in the hash as shared variable to the configuration.voidsetAutoImports(Map<String, String> map) set a map of namespace names to templates for auto-importing a set of templates.voidsetAutoIncludes(List<String> templateNames) set the list of automatically included templates.voidsetAutoTemplateVisitors(freemarker.core.ast.ASTVisitor... visitors) voidsetCacheStorage(CacheStorage storage) voidsetClassForTemplateLoading(Class clazz, String pathPrefix) Sets a class relative to which we do the Class.getResource() call to load templates.static voidsetDefaultConfiguration(Configuration config) Deprecated.Using the "default"Configurationinstance can easily lead to erroneous, unpredictable behaviour.voidsetDefaultEncoding(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.voidSet the explicit directory from which to load templates.voidsetEncoding(Locale locale, String encoding) Sets the character set encoding to use for templates of a given locale.voidsetLocalizedLookup(boolean localizedLookup) Enables/disables localized template lookup.voidsetSecure(boolean secure) Sets whether templates are secured.voidsetServletContextForTemplateLoading(Object sctxt, String path) Sets the servlet context from which to load templatesvoidsetSetting(String key, String value) Sets a setting by name and string value.voidsetSharedVariable(String name, TemplateModel tm) Adds a shared variable to the configuration.voidsetSharedVariable(String name, Object obj) Adds shared variable to the configuration.voidsetStrictVariableDefinition(boolean b) Sets whether, by default, templates use strict variable definition syntax, such that any variable created at the top template level must be declared with a #var directive.voidsetTagSyntax(int tagSyntax) Determines the syntax of the template files (angle bracket VS square bracket) that has noftl directive in it.voidsetTemplateCache(TemplateCache cache) voidsetTemplateLoader(TemplateLoader loader) Sets a template loader that is used to look up and load templates.voidsetTemplateUpdateDelay(int delay) Set the time in seconds that must elapse before checking whether there is a newer version of a template file.voidsetTolerateParsingProblems(boolean tolerateParsingProblems) Set whether the getTemplate() methods throw exceptions when there is a (recoverable) parsing problem in the template.voidsetWhitespaceStripping(boolean b) Sets whether the FTL parser will try to remove superfluous white-space around certain FTL tags.intsize()values()Methods inherited from class freemarker.core.Configurable
getArithmeticEngine, getBooleanFormat, getBooleanFormat, getCustomAttribute, getCustomAttributeNames, getDateFormat, getDateTimeFormat, getEnvironment, getLocale, getNumberFormat, getObjectWrapper, getOutputEncoding, getParent, getSetting, getSettings, getTemplateExceptionHandler, getTimeFormat, getTimeZone, getURLEscapingCharset, invalidSettingValueException, removeCustomAttribute, setArithmeticEngine, setBooleanFormat, setCustomAttribute, setDateFormat, setDateTimeFormat, setLocale, setNumberFormat, setNumbersForComputers, setObjectWrapper, setOutputEncoding, setParent, setSettings, setSettings, setStrictBeanModels, setTemplateExceptionHandler, setTimeFormat, setTimeZone, setURLEscapingCharset, unknownSettingExceptionMethods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface freemarker.core.Scope
getEnvironment
-
Field Details
-
DEFAULT_ENCODING_KEY
- See Also:
-
LOCALIZED_LOOKUP_KEY
- See Also:
-
STRICT_SYNTAX_KEY
- See Also:
-
WHITESPACE_STRIPPING_KEY
- See Also:
-
CACHE_STORAGE_KEY
- See Also:
-
TEMPLATE_UPDATE_DELAY_KEY
- See Also:
-
AUTO_IMPORT_KEY
- See Also:
-
AUTO_INCLUDE_KEY
- See Also:
-
STRICT_VARS_KEY
- See Also:
-
SECURE
- See Also:
-
AUTO_DETECT_TAG_SYNTAX
public static final int AUTO_DETECT_TAG_SYNTAX- See Also:
-
ANGLE_BRACKET_TAG_SYNTAX
public static final int ANGLE_BRACKET_TAG_SYNTAX- See Also:
-
SQUARE_BRACKET_TAG_SYNTAX
public static final int SQUARE_BRACKET_TAG_SYNTAX- See Also:
-
-
Constructor Details
-
Configuration
public Configuration()
-
-
Method Details
-
setTemplateCache
-
getTemplateCache
-
clone
- Overrides:
clonein classConfigurable
-
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:ar ISO-8859-6 be ISO-8859-5 bg ISO-8859-5 ca ISO-8859-1 cs ISO-8859-2 da ISO-8859-1 de ISO-8859-1 el ISO-8859-7 en ISO-8859-1 es ISO-8859-1 et ISO-8859-1 fi ISO-8859-1 fr ISO-8859-1 hr ISO-8859-2 hu ISO-8859-2 is ISO-8859-1 it ISO-8859-1 iw ISO-8859-8 ja Shift_JIS ko EUC-KR lt ISO-8859-2 lv ISO-8859-2 mk ISO-8859-5 nl ISO-8859-1 no ISO-8859-1 pl ISO-8859-2 pt ISO-8859-1 ro ISO-8859-2 ru ISO-8859-5 sh ISO-8859-5 sk ISO-8859-2 sl ISO-8859-2 sq ISO-8859-2 sr ISO-8859-5 sv ISO-8859-1 tr ISO-8859-9 uk ISO-8859-5 zh GB2312 zh_TW Big5 -
clearEncodingMap
public void clearEncodingMap()Clears language-to-encoding map. -
getDefaultConfiguration
Deprecated.The usage of the static singleton (the "default")Configurationinstance 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 commonConfigurationinstance. Each such component should use its own privateConfigurationobject instead, that it typically creates withnew 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. -
getCurrentConfiguration
- Returns:
- the
Configurationobject that is being used in this template processing thread.
-
getCurrentObjectWrapper
- Returns:
- the
ObjectWrapperobject that is being used in this template processing thread.
-
setDefaultConfiguration
Deprecated.Using the "default"Configurationinstance can easily lead to erroneous, unpredictable behaviour. See morehere....Sets the Configuration object that will be retrieved from future calls togetDefaultConfiguration(). -
setTemplateLoader
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), andsetServletContextForTemplateLoading(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.- Throws:
SecurityException- if there is aSecurityManagerin the JVM,isSecure()is true and the calling code doesn't have the "setTemplateLoader"FreeMarkerPermission
-
getTemplateLoader
- Returns:
- the template loader that is used to look up and load templates.
- See Also:
-
setCacheStorage
-
setDirectoryForTemplateLoading
Set the explicit directory from which to load templates.- Throws:
IOException
-
setServletContextForTemplateLoading
Sets the servlet context from which to load templates- Parameters:
sctxt- the ServletContext object. Note that the type isObjectto 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
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. -
setTagSyntax
public void setTagSyntax(int tagSyntax) Determines the syntax of the template files (angle bracket VS square bracket) that has noftl directive in it. ThetagSyntaxparameter must be one of:AUTO_DETECT_TAG_SYNTAX: use the syntax of the first FreeMarker tag (can be anything, like list, include, user defined, ...etc)ANGLE_BRACKET_TAG_SYNTAX: use the angle bracket syntax (the normal syntax)SQUARE_BRACKET_TAG_SYNTAX: use the square bracket syntax
In FreeMarker 2.3.x
ANGLE_BRACKET_TAG_SYNTAXis the default for better backward compatibility. Starting from 2.4.xAUTO_DETECT_TAG_SYNTAXis 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:
- one of:
AUTO_DETECT_TAG_SYNTAX: use the syntax of the first FreeMarker tag (can be anything, like list, include, user defined, ...etc)ANGLE_BRACKET_TAG_SYNTAX: use the angle bracket syntax (the normal syntax)SQUARE_BRACKET_TAG_SYNTAX: use the square bracket syntax
-
setStrictVariableDefinition
public void setStrictVariableDefinition(boolean b) Sets whether, by default, templates use strict variable definition syntax, such that any variable created at the top template level must be declared with a #var directive. At the moment, the factory-set default is on. -
getStrictVariableDefinition
public boolean getStrictVariableDefinition()- Returns:
- whether, by default, templates use strict variable definition syntax, such that any variable created at the top template level must be declared with a #var directive. At the moment, the factory-set default is on.
-
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:
-
getTemplate
Equivalent to getTemplate(name, thisCfg.getLocale(), thisCfg.getEncoding(thisCfg.getLocale()), true).- Throws:
IOException
-
getTemplate
Equivalent to getTemplate(name, locale, thisCfg.getEncoding(locale), true).- Throws:
IOException
-
getTemplate
Equivalent to getTemplate(name, thisCfg.getLocale(), encoding, true).- Throws:
IOException
-
getTemplate
Equivalent to getTemplate(name, locale, encoding, true).- Throws:
IOException
-
getTemplate
public Template getTemplate(String name, Locale locale, String encoding, boolean parse) throws 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, seeTemplateCache.getTemplate(String, Locale, String, boolean).- Returns:
- the requested template.
- Throws:
FileNotFoundException- if the template could not be found.IOException- if there was a problem loading the template.freemarker.core.parser.ParseException- (extendsIOException) if the template is syntactically bad.
-
setDefaultEncoding
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
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
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 usingsetEncoding(Locale, String)orloadBuiltInEncodingMap().- Parameters:
loc- the locale- Returns:
- the preferred character encoding for the locale.
-
setEncoding
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 withsetDefaultEncoding(java.lang.String).- See Also:
-
clearTemplateCache
public void clearTemplateCache()Removes all entries from the template cache, thus forcing reloading of templates on subsequentgetTemplatecalls. 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
Sets a setting by name and string value. In additional to the settings understood bythe super method, it understands these:"auto_import": Sets the list of auto-imports. Example of valid value:/lib/form.ftl as f, /lib/widget as w, "/lib/evil name.ftl" as oddSee:setAutoImports(java.util.Map<java.lang.String, java.lang.String>)"auto_include": Sets the list of auto-includes. Example of valid value:/include/common.ftl, "/include/evil name.ftl"See:setAutoIncludes(java.util.List<java.lang.String>)"default_encoding": The name of the charset, such as"UTF-8". See:setDefaultEncoding(java.lang.String)"localized_lookup":"true","false","yes","no","t","f","y","n". Case insensitive. See:setLocalizedLookup(boolean)"strict_vars":"true","false", etc. See:setStrictVariableDefinition(boolean)"whitespace_stripping":"true","false", etc. See:setWhitespaceStripping(boolean)"cache_storage": If the value contains dot, then it is interpreted as class name, and the object will be created with its parameterless constructor. If the value does not contain dot, then aMruCacheStoragewill be used with the maximum strong and soft sizes specified with the setting value. Examples of valid setting values:
The value is not case sensitive. The order of soft and strong entries is not significant. See also:Setting value max. strong size max. soft size "strong:50, soft:500"50 500 "strong:100, soft"100 Integer.MAX_VALUE"strong:100"100 0 "soft:100"0 100 "strong"Integer.MAX_VALUE0 "soft"0 Integer.MAX_VALUEsetCacheStorage(freemarker.cache.CacheStorage)"template_update_delay": Valid positive integer, the update delay measured in seconds. See:setTemplateUpdateDelay(int)
- Overrides:
setSettingin classConfigurable- Parameters:
key- the name of the setting.value- the string that describes the new value of the setting.- Throws:
Configurable.UnknownSettingException- if the key is wrong.TemplateException- if the new value of the setting can't be set for any other reasons.
-
addAutoImport
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 importedtemplate- the name of the template
-
removeAutoImport
Remove an auto-imported template- Parameters:
namespace- the name of the namespace into which the template was imported
-
setAutoImports
set a map of namespace names to templates for auto-importing a set of templates. Note that all previous auto-imports are removed. -
doAutoImportsAndIncludes
- Overrides:
doAutoImportsAndIncludesin classConfigurable- Throws:
TemplateExceptionIOException
-
addAutoInclude
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
set the list of automatically included templates. Note that all previous auto-includes are removed. -
removeAutoInclude
remove a template from the auto-include list.- Parameters:
templateName- the lookup name of the template in question.
-
addAutoTemplateVisitors
public void addAutoTemplateVisitors(freemarker.core.ast.ASTVisitor... visitors) -
removeAutoTemplateVisitors
public void removeAutoTemplateVisitors(freemarker.core.ast.ASTVisitor... visitors) -
setAutoTemplateVisitors
public void setAutoTemplateVisitors(freemarker.core.ast.ASTVisitor... visitors) -
setSecure
public void setSecure(boolean secure) Sets whether templates are secured. When templates are secured, they are executing in a protection domain determined by their code source. SeeSecureTemplateLoaderand its implementations for details. When templates are not secured, they are executing in the protection domain of FreeMarker libraries. If your deployment execution of templates from sources you don't control, you should consider using the secured templates feature.- Parameters:
secure-- Throws:
SecurityException- if there is aSecurityManagerin the JVM,isSecure()is true and the calling code doesn't have the "setSecure"FreeMarkerPermission
-
isSecure
public boolean isSecure() -
getVersionNumber
Returns FreeMarker version. -
setTolerateParsingProblems
public void setTolerateParsingProblems(boolean tolerateParsingProblems) Set whether the getTemplate() methods throw exceptions when there is a (recoverable) parsing problem in the template. This would only be set true by certain tools such as FTL-aware editors that work with FTL code that contains syntactical errors.- Parameters:
tolerateParsingProblems-
-
getEnclosingScope
- Specified by:
getEnclosingScopein interfaceScope- Returns:
- null The Configuration is the final fallback scope. It has no enclosing scope.
-
definesVariable
- Specified by:
definesVariablein interfaceScope- Returns:
- whether the variable is defined in this specific scope. (It could be defined in a fallback scope and this method will return false.)
-
getTemplate
- Specified by:
getTemplatein interfaceScope- Returns:
- null The Configuration object is not associated with a template.
-
put
Description copied from interface:ScopeSet a variable in this scope. This will typically only be used internally by the FreeMarker engine. -
get
Description copied from interface:TemplateHashModelGets a TemplateModel from the hash.- Specified by:
getin interfaceTemplateHashModel- Parameters:
name- the name by which the TemplateModel is identified in the template.- Returns:
- the TemplateModel referred to by the key, or null if not found.
-
resolveVariable
Description copied from interface:ScopeEvaluates the variable of this name in this scope, falling back to the enclosing Scope if it is not defined in this one.- Specified by:
resolveVariablein interfaceScope
-
getDirectVariableNames
Description copied from interface:ScopeReturns the names of variables directly managed by this scope (i.e. it does not traverse the chain of enclosing scopes, but limits itself to this scope only).- Specified by:
getDirectVariableNamesin interfaceScope- Returns:
- a collection of known variable names for this scope, without enclosing scopes. The returned collection should be either immutable, or it should be disconnected from the scope, so any modifications to the collection don't affect the scope.
-
remove
Description copied from interface:ScopeRemoves a variable in this scope. This will typically only be used by FreeMarker engine internals -
isEmpty
public boolean isEmpty()- Specified by:
isEmptyin interfaceTemplateHashModel
-
size
public int size()- Specified by:
sizein interfaceTemplateHashModelEx- Returns:
- the number of key/value mappings in the hash.
-
keys
- Specified by:
keysin interfaceTemplateHashModelEx- Returns:
- a collection containing the keys in the hash. Every element of
the returned collection must implement the
TemplateScalarModel(as the keys of hashes are always strings).
-
values
- Specified by:
valuesin interfaceTemplateHashModelEx- Returns:
- a collection containing the values in the hash.
-
enableRhino
public boolean enableRhino()We're keeping this functionality for now, but if there is no sign anybody is interested in using this, it will likely be removed.- Returns:
- whether successful
-
enableJython
public boolean enableJython()We're keeping this functionality for now, but if there is no sign anybody is interested in using this, it will likely be removed.- Returns:
- whether successful
-
enableJRuby
public boolean enableJRuby()We're keeping this functionality for now, but if there is no sign anybody is interested in using this, it will likely be removed.- Returns:
- whether successful
-
Configurationinstance can easily cause erroneous, unpredictable behavior.