freemarker.core
Class Environment

java.lang.Object
  extended by freemarker.core.Configurable
      extended by freemarker.core.Environment

public final class Environment
extends Configurable

Object that represents the runtime environment during template processing. For every invocation of a Template.process() method, a new instance of this object is created, and then discarded when process() returns. This object stores the set of temporary variables created by the template, the value of settings set by the template, the reference to the data model root, etc. Everything that is needed to fulfill the template processing job.

Data models that need to access the Environment object that represents the template processing on the current thread can use the getCurrentEnvironment() method.

If you need to modify or read this object before or after the process call, use Template.createProcessingEnvironment(Object rootMap, Writer out, ObjectWrapper wrapper)

Author:
Jonathan Revusky, Attila Szegedi

Nested Class Summary
 class Environment.Namespace
           
 
Nested classes/interfaces inherited from class freemarker.core.Configurable
Configurable.UnknownSettingException
 
Field Summary
 
Fields inherited from class freemarker.core.Configurable
ARITHMETIC_ENGINE_KEY, AUTO_FLUSH_KEY, BOOLEAN_FORMAT_KEY, CLASSIC_COMPATIBLE_KEY, DATE_FORMAT_KEY, DATETIME_FORMAT_KEY, LOCALE_KEY, NEW_BUILTIN_CLASS_RESOLVER_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
Environment(Template template, TemplateHashModel rootDataModel, java.io.Writer out)
           
 
Method Summary
 java.lang.Object __getitem__(java.lang.String key)
          A hook that Jython uses.
 void __setitem__(java.lang.String key, java.lang.Object o)
          A hook that Jython uses.
 java.text.NumberFormat getCNumberFormat()
          Returns the NumberFormat used for the c built-in.
 Configuration getConfiguration()
           
static Environment getCurrentEnvironment()
          Retrieves the environment object associated with the current thread.
 Environment.Namespace getCurrentNamespace()
          Returns the main name-space.
 TemplateNodeModel getCurrentVisitorNode()
           
 TemplateHashModel getDataModel()
           
 java.lang.String getDefaultNS()
           
 Environment.Namespace getGlobalNamespace()
          Returns a fictitious name-space that contains the globally visible variables that were created in the template, but not the variables of the data-model.
 TemplateModel getGlobalVariable(java.lang.String name)
          Returns the globally visible variable of the given name (or null).
 TemplateHashModel getGlobalVariables()
          Returns the read-only hash of globally visible variables.
 java.util.Set getKnownVariableNames()
          Returns a set of variable names that are known at the time of call.
 TemplateModel getLocalVariable(java.lang.String name)
          Returns the loop or macro local variable corresponding to this variable name.
 Environment.Namespace getMainNamespace()
          Returns the main name-space.
 Environment.Namespace getNamespace(java.lang.String name)
          Returns the name-space for the name if exists, or null.
 java.lang.String getNamespaceForPrefix(java.lang.String prefix)
           
 java.io.Writer getOut()
           
 java.lang.String getPrefixForNamespace(java.lang.String nsURI)
           
 Template getTemplate()
          Retrieves the currently processed template.
 Template getTemplateForImporting(java.lang.String name)
          Gets a template for importing; used with importLib(Template importedTemplate, String namespace).
 Template getTemplateForInclusion(java.lang.String name, java.lang.String encoding, boolean parse)
          Gets a template for inclusion; used with include(Template includedTemplate).
 TemplateModel getVariable(java.lang.String name)
          Returns the variable that is visible in this context.
 Environment.Namespace importLib(java.lang.String name, java.lang.String namespace)
          Emulates import directive, except that name must be tempate root relative.
 Environment.Namespace importLib(Template loadedTemplate, java.lang.String namespace)
          Emulates import directive.
 void include(java.lang.String name, java.lang.String encoding, boolean parse)
          Emulates include directive, except that name must be tempate root relative.
 void include(Template includedTemplate)
          Processes a Template in the context of this Environment, including its output in the Environment's Writer.
 void outputInstructionStack(java.io.PrintWriter pw)
          Outputs the instruction stack.
 void process()
          Processes the template to which this environment belongs.
 void setCurrentVisitorNode(TemplateNodeModel node)
          sets TemplateNodeModel as the current visitor node.
 void setDateFormat(java.lang.String formatName)
          Sets the date format used to convert date models representing date-only dates to strings.
 void setDateTimeFormat(java.lang.String formatName)
          Sets the date format used to convert date models representing datetime dates to strings.
 void setGlobalVariable(java.lang.String name, TemplateModel model)
          Sets a variable that is visible globally.
 void setLocale(java.util.Locale locale)
          Sets the locale to assume when searching for template files with no explicit requested locale.
 void setLocalVariable(java.lang.String name, TemplateModel model)
          Sets a local variable (one effective only during a macro invocation).
 void setNumberFormat(java.lang.String formatName)
          Sets the number format used to convert numbers to strings.
 void setOut(java.io.Writer out)
           
 void setOutputEncoding(java.lang.String outputEncoding)
          Sets the output encoding.
 void setTemplateExceptionHandler(TemplateExceptionHandler templateExceptionHandler)
          Sets the exception handler used to handle template exceptions.
 void setTimeFormat(java.lang.String formatName)
          Sets the date format used to convert date models representing time-only values to strings.
 void setTimeZone(java.util.TimeZone timeZone)
          Sets the time zone to use when formatting time values.
 void setURLEscapingCharset(java.lang.String urlEscapingCharset)
          Sets the URL escaping charset.
 void setVariable(java.lang.String name, TemplateModel model)
          Sets a variable in the current namespace.
 void visit(TemplateElement element, TemplateDirectiveModel directiveModel, java.util.Map args, java.util.List bodyParameterNames)
           
 
Methods inherited from class freemarker.core.Configurable
clone, doAutoImportsAndIncludes, getArithmeticEngine, getAutoFlush, getBooleanFormat, getCustomAttribute, getCustomAttributeNames, getDateFormat, getDateTimeFormat, getEnvironment, getLocale, getNewBuiltinClassResolver, getNumberFormat, getObjectWrapper, getOutputEncoding, getParent, getSetting, getSettings, getTemplateExceptionHandler, getTimeFormat, getTimeZone, getURLEscapingCharset, invalidSettingValueException, isClassicCompatible, parseAsImportList, parseAsList, parseAsSegmentedList, removeCustomAttribute, setArithmeticEngine, setAutoFlush, setBooleanFormat, setClassicCompatible, setCustomAttribute, setNewBuiltinClassResolver, setObjectWrapper, setSetting, setSettings, setSettings, setStrictBeanModels, unknownSettingException
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Environment

public Environment(Template template,
                   TemplateHashModel rootDataModel,
                   java.io.Writer out)
Method Detail

getCurrentEnvironment

public static Environment getCurrentEnvironment()
Retrieves the environment object associated with the current thread. Data model implementations that need access to the environment can call this method to obtain the environment object that represents the template processing that is currently running on the current thread.


getTemplate

public Template getTemplate()
Retrieves the currently processed template.


process

public void process()
             throws TemplateException,
                    java.io.IOException
Processes the template to which this environment belongs.

Throws:
TemplateException
java.io.IOException

visit

public void visit(TemplateElement element,
                  TemplateDirectiveModel directiveModel,
                  java.util.Map args,
                  java.util.List bodyParameterNames)
           throws TemplateException,
                  java.io.IOException
Throws:
TemplateException
java.io.IOException

setTemplateExceptionHandler

public void setTemplateExceptionHandler(TemplateExceptionHandler templateExceptionHandler)
Description copied from class: Configurable
Sets the exception handler used to handle template exceptions.

Overrides:
setTemplateExceptionHandler in class Configurable
Parameters:
templateExceptionHandler - the template exception handler to use for handling TemplateExceptions. By default, TemplateExceptionHandler.HTML_DEBUG_HANDLER is used.

setLocale

public void setLocale(java.util.Locale locale)
Description copied from class: Configurable
Sets the locale to assume when searching for template files with no explicit requested locale.

Overrides:
setLocale in class Configurable

setTimeZone

public void setTimeZone(java.util.TimeZone timeZone)
Description copied from class: Configurable
Sets the time zone to use when formatting time values.

Overrides:
setTimeZone in class Configurable

setURLEscapingCharset

public void setURLEscapingCharset(java.lang.String urlEscapingCharset)
Description copied from class: Configurable
Sets the URL escaping charset. Allows null, which means that the output encoding will be used for URL escaping.

Overrides:
setURLEscapingCharset in class Configurable

setOutputEncoding

public void setOutputEncoding(java.lang.String outputEncoding)
Description copied from class: Configurable
Sets the output encoding. Allows null, which means that the output encoding is not known.

Overrides:
setOutputEncoding in class Configurable

setOut

public void setOut(java.io.Writer out)

getOut

public java.io.Writer getOut()

setNumberFormat

public void setNumberFormat(java.lang.String formatName)
Description copied from class: Configurable
Sets the number format used to convert numbers to strings.

Overrides:
setNumberFormat in class Configurable

setTimeFormat

public void setTimeFormat(java.lang.String formatName)
Description copied from class: Configurable
Sets the date format used to convert date models representing time-only values to strings.

Overrides:
setTimeFormat in class Configurable

setDateFormat

public void setDateFormat(java.lang.String formatName)
Description copied from class: Configurable
Sets the date format used to convert date models representing date-only dates to strings.

Overrides:
setDateFormat in class Configurable

setDateTimeFormat

public void setDateTimeFormat(java.lang.String formatName)
Description copied from class: Configurable
Sets the date format used to convert date models representing datetime dates to strings.

Overrides:
setDateTimeFormat in class Configurable

getConfiguration

public Configuration getConfiguration()

getCNumberFormat

public java.text.NumberFormat getCNumberFormat()
Returns the NumberFormat used for the c built-in. This is always US English "0.################", without grouping and without superfluous decimal separator.


getLocalVariable

public TemplateModel getLocalVariable(java.lang.String name)
                               throws TemplateModelException
Returns the loop or macro local variable corresponding to this variable name. Possibly null. (Note that the misnomer is kept for backward compatibility: loop variables are not local variables according to our terminology.)

Throws:
TemplateModelException

getVariable

public TemplateModel getVariable(java.lang.String name)
                          throws TemplateModelException
Returns the variable that is visible in this context. This is the correspondent to an FTL top-level variable reading expression. That is, it tries to find the the variable in this order:
  1. An loop variable (if we're in a loop or user defined directive body) such as foo_has_next
  2. A local variable (if we're in a macro)
  3. A variable defined in the current namespace (say, via <#assign ...>)
  4. A variable defined globally (say, via <#global ....>)
  5. Variable in the data model:
    1. A variable in the root hash that was exposed to this rendering environment in the Template.process(...) call
    2. A shared variable set in the configuration via a call to Configuration.setSharedVariable(...)

Throws:
TemplateModelException

getGlobalVariable

public TemplateModel getGlobalVariable(java.lang.String name)
                                throws TemplateModelException
Returns the globally visible variable of the given name (or null). This is correspondent to FTL .globals.name. This will first look at variables that were assigned globally via: <#global ...> and then at the data model exposed to the template.

Throws:
TemplateModelException

setGlobalVariable

public void setGlobalVariable(java.lang.String name,
                              TemplateModel model)
Sets a variable that is visible globally. This is correspondent to FTL <#global name=model>. This can be considered a convenient shorthand for: getGlobalNamespace().put(name, model)


setVariable

public void setVariable(java.lang.String name,
                        TemplateModel model)
Sets a variable in the current namespace. This is correspondent to FTL <#assign name=model>. This can be considered a convenient shorthand for: getCurrentNamespace().put(name, model)


setLocalVariable

public void setLocalVariable(java.lang.String name,
                             TemplateModel model)
Sets a local variable (one effective only during a macro invocation). This is correspondent to FTL <#local name=model>.

Parameters:
name - the identifier of the variable
model - the value of the variable.
Throws:
java.lang.IllegalStateException - if the environment is not executing a macro body.

getKnownVariableNames

public java.util.Set getKnownVariableNames()
                                    throws TemplateModelException
Returns a set of variable names that are known at the time of call. This includes names of all shared variables in the Configuration, names of all global variables that were assigned during the template processing, names of all variables in the current name-space, names of all local variables and loop variables. If the passed root data model implements the TemplateHashModelEx interface, then all names it retrieves through a call to TemplateHashModelEx.keys() method are returned as well. The method returns a new Set object on each call that is completely disconnected from the Environment. That is, modifying the set will have no effect on the Environment object.

Throws:
TemplateModelException

outputInstructionStack

public void outputInstructionStack(java.io.PrintWriter pw)
Outputs the instruction stack. Useful for debugging. TemplateExceptions incorporate this information in their stack traces.


getNamespace

public Environment.Namespace getNamespace(java.lang.String name)
Returns the name-space for the name if exists, or null.

Parameters:
name - the template path that you have used with the import directive or importLib(String, String) call, in normalized form. That is, the path must be an absolute path, and it must not contain "/../" or "/./". The leading "/" is optional.

getMainNamespace

public Environment.Namespace getMainNamespace()
Returns the main name-space. This is correspondent of FTL .main hash.


getCurrentNamespace

public Environment.Namespace getCurrentNamespace()
Returns the main name-space. This is correspondent of FTL .namespace hash.


getGlobalNamespace

public Environment.Namespace getGlobalNamespace()
Returns a fictitious name-space that contains the globally visible variables that were created in the template, but not the variables of the data-model. There is no such thing in FTL; this strange method was added because of the JSP taglib support, since this imaginary name-space contains the page-scope attributes.


getDataModel

public TemplateHashModel getDataModel()

getGlobalVariables

public TemplateHashModel getGlobalVariables()
Returns the read-only hash of globally visible variables. This is the correspondent of FTL .globals hash. That is, you see the variables created with <#global ...>, and the variables of the data-model. To create new global variables, use setGlobalVariable.


getCurrentVisitorNode

public TemplateNodeModel getCurrentVisitorNode()

setCurrentVisitorNode

public void setCurrentVisitorNode(TemplateNodeModel node)
sets TemplateNodeModel as the current visitor node. .current_node


include

public void include(java.lang.String name,
                    java.lang.String encoding,
                    boolean parse)
             throws java.io.IOException,
                    TemplateException
Emulates include directive, except that name must be tempate root relative.

It's the same as include(getTemplateForInclusion(name, encoding, parse)). But, you may want to separately call these two methods, so you can determine the source of exceptions more precisely, and thus achieve more intelligent error handling.

Throws:
java.io.IOException
TemplateException
See Also:
getTemplateForInclusion(String name, String encoding, boolean parse), include(Template includedTemplate)

getTemplateForInclusion

public Template getTemplateForInclusion(java.lang.String name,
                                        java.lang.String encoding,
                                        boolean parse)
                                 throws java.io.IOException
Gets a template for inclusion; used with include(Template includedTemplate). The advantage over simply using config.getTemplate(...) is that it chooses the default encoding as the include directive does.

Parameters:
name - the name of the template, relatively to the template root directory (not the to the directory of the currently executing template file!). (Note that you can use TemplateCache.getFullTemplatePath(freemarker.core.Environment, java.lang.String, java.lang.String) to convert paths to template root relative paths.)
encoding - the encoding of the obtained template. If null, the encoding of the Template that is currently being processed in this Environment is used.
parse - whether to process a parsed template or just include the unparsed template source.
Throws:
java.io.IOException

include

public void include(Template includedTemplate)
             throws TemplateException,
                    java.io.IOException
Processes a Template in the context of this Environment, including its output in the Environment's Writer.

Parameters:
includedTemplate - the template to process. Note that it does not need to be a template returned by getTemplateForInclusion(String name, String encoding, boolean parse).
Throws:
TemplateException
java.io.IOException

importLib

public Environment.Namespace importLib(java.lang.String name,
                                       java.lang.String namespace)
                                throws java.io.IOException,
                                       TemplateException
Emulates import directive, except that name must be tempate root relative.

It's the same as importLib(getTemplateForImporting(name), namespace). But, you may want to separately call these two methods, so you can determine the source of exceptions more precisely, and thus achieve more intelligent error handling.

Throws:
java.io.IOException
TemplateException
See Also:
getTemplateForImporting(String name), importLib(Template includedTemplate, String namespace)

getTemplateForImporting

public Template getTemplateForImporting(java.lang.String name)
                                 throws java.io.IOException
Gets a template for importing; used with importLib(Template importedTemplate, String namespace). The advantage over simply using config.getTemplate(...) is that it chooses the encoding as the import directive does.

Parameters:
name - the name of the template, relatively to the template root directory (not the to the directory of the currently executing template file!). (Note that you can use TemplateCache.getFullTemplatePath(freemarker.core.Environment, java.lang.String, java.lang.String) to convert paths to template root relative paths.)
Throws:
java.io.IOException

importLib

public Environment.Namespace importLib(Template loadedTemplate,
                                       java.lang.String namespace)
                                throws java.io.IOException,
                                       TemplateException
Emulates import directive.

Parameters:
loadedTemplate - the template to import. Note that it does not need to be a template returned by getTemplateForImporting(String name).
Throws:
java.io.IOException
TemplateException

getNamespaceForPrefix

public java.lang.String getNamespaceForPrefix(java.lang.String prefix)
Returns:
the namespace URI registered for this prefix, or null. This is based on the mappings registered in the current namespace.

getPrefixForNamespace

public java.lang.String getPrefixForNamespace(java.lang.String nsURI)

getDefaultNS

public java.lang.String getDefaultNS()
Returns:
the default node namespace for the current FTL namespace

__getitem__

public java.lang.Object __getitem__(java.lang.String key)
                             throws TemplateModelException
A hook that Jython uses.

Throws:
TemplateModelException

__setitem__

public void __setitem__(java.lang.String key,
                        java.lang.Object o)
                 throws TemplateException
A hook that Jython uses.

Throws:
TemplateException