Class Configuration

java.lang.Object
freemarker.core.Configurable
freemarker.template.Configuration
All Implemented Interfaces:
Scope, TemplateHashModel, TemplateHashModelEx, TemplateModel, Cloneable

public class Configuration extends Configurable implements Cloneable, Scope
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.
  • Field Details

  • Constructor Details

    • Configuration

      public Configuration()
  • Method Details

    • setTemplateCache

      public void setTemplateCache(TemplateCache cache)
    • getTemplateCache

      public TemplateCache getTemplateCache()
    • clone

      public 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

      public void clearEncodingMap()
      Clears language-to-encoding map.
      See Also:
    • 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.
    • getCurrentConfiguration

      public static Configuration getCurrentConfiguration()
      Returns:
      the Configuration object that is being used in this template processing thread.
    • getCurrentObjectWrapper

      public static ObjectWrapper getCurrentObjectWrapper()
      Returns:
      the ObjectWrapper object that is being used in this template processing thread.
    • 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.
      Throws:
      SecurityException - if there is a SecurityManager in the JVM, isSecure() is true and the calling code doesn't have the "setTemplateLoader" FreeMarkerPermission
    • getTemplateLoader

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

      public void setCacheStorage(CacheStorage storage)
    • setDirectoryForTemplateLoading

      public void setDirectoryForTemplateLoading(File dir) throws IOException
      Set the explicit directory from which to load templates.
      Throws:
      IOException
    • setServletContextForTemplateLoading

      public void setServletContextForTemplateLoading(Object sctxt, 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(Class clazz, 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.
    • 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:
      one of:
    • 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

      public Template getTemplate(String name) throws IOException
      Equivalent to getTemplate(name, thisCfg.getLocale(), thisCfg.getEncoding(thisCfg.getLocale()), true).
      Throws:
      IOException
    • getTemplate

      public Template getTemplate(String name, Locale locale) throws IOException
      Equivalent to getTemplate(name, locale, thisCfg.getEncoding(locale), true).
      Throws:
      IOException
    • getTemplate

      public Template getTemplate(String name, String encoding) throws IOException
      Equivalent to getTemplate(name, thisCfg.getLocale(), encoding, true).
      Throws:
      IOException
    • getTemplate

      public Template getTemplate(String name, Locale locale, String encoding) throws IOException
      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, see TemplateCache.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 - (extends IOException) if the template is syntactically bad.
    • setDefaultEncoding

      public void setDefaultEncoding(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 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 String 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. 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(Locale locale, 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:
    • setSharedVariable

      public void setSharedVariable(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:
    • getSharedVariableNames

      public Set<String> 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(String name, Object obj) throws TemplateModelException
      Adds shared variable to the configuration. It uses Configurable.getObjectWrapper() to wrap the obj.
      Throws:
      TemplateModelException
      See Also:
    • 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:
    • getSharedVariable

      public TemplateModel getSharedVariable(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:
    • 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(String key, 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:
      Configurable.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(String namespace, 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(String namespace)
      Remove an auto-imported template
      Parameters:
      namespace - the name of the namespace into which the template was imported
    • setAutoImports

      public void setAutoImports(Map<String,String> map)
      set a map of namespace names to templates for auto-importing a set of templates. Note that all previous auto-imports are removed.
    • doAutoImportsAndIncludes

      protected void doAutoImportsAndIncludes(Environment env) throws TemplateException, IOException
      Overrides:
      doAutoImportsAndIncludes in class Configurable
      Throws:
      TemplateException
      IOException
    • addAutoInclude

      public void addAutoInclude(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(List<String> templateNames)
      set the list of automatically included templates. Note that all previous auto-includes are removed.
    • removeAutoInclude

      public void removeAutoInclude(String templateName)
      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. See SecureTemplateLoader and 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 a SecurityManager in the JVM, isSecure() is true and the calling code doesn't have the "setSecure" FreeMarkerPermission
    • isSecure

      public boolean isSecure()
    • getVersionNumber

      public static String 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

      public Scope getEnclosingScope()
      Specified by:
      getEnclosingScope in interface Scope
      Returns:
      null The Configuration is the final fallback scope. It has no enclosing scope.
    • definesVariable

      public boolean definesVariable(String name)
      Specified by:
      definesVariable in interface Scope
      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

      public Template getTemplate()
      Specified by:
      getTemplate in interface Scope
      Returns:
      null The Configuration object is not associated with a template.
    • put

      public void put(String varname, TemplateModel value)
      Description copied from interface: Scope
      Set a variable in this scope. This will typically only be used internally by the FreeMarker engine.
      Specified by:
      put in interface Scope
    • get

      public TemplateModel get(String name)
      Description copied from interface: TemplateHashModel
      Gets a TemplateModel from the hash.
      Specified by:
      get in interface TemplateHashModel
      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

      public TemplateModel resolveVariable(String name)
      Description copied from interface: Scope
      Evaluates the variable of this name in this scope, falling back to the enclosing Scope if it is not defined in this one.
      Specified by:
      resolveVariable in interface Scope
    • getDirectVariableNames

      public Collection<String> getDirectVariableNames()
      Description copied from interface: Scope
      Returns 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:
      getDirectVariableNames in interface Scope
      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

      public TemplateModel remove(String varname)
      Description copied from interface: Scope
      Removes a variable in this scope. This will typically only be used by FreeMarker engine internals
      Specified by:
      remove in interface Scope
    • isEmpty

      public boolean isEmpty()
      Specified by:
      isEmpty in interface TemplateHashModel
    • size

      public int size()
      Specified by:
      size in interface TemplateHashModelEx
      Returns:
      the number of key/value mappings in the hash.
    • keys

      public TemplateCollectionModel keys()
      Specified by:
      keys in interface TemplateHashModelEx
      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

      public TemplateCollectionModel values()
      Specified by:
      values in interface TemplateHashModelEx
      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