Class Environment
- All Implemented Interfaces:
Scope,TemplateHashModel,TemplateHashModelEx,TemplateModel
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)
-
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
FieldsFields 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 TypeMethodDescription__getitem__(String key) A hook that Jython uses.void__setitem__(String key, Object o) A hook that Jython uses.booleandefinesVariable(String name) voidfallback()formatDate(Date date, int type) formatNumber(Number number) This method returns a variable from the "global" namespace and falls back to the data model.Returns theNumberFormatused for the c built-in.static EnvironmentRetrieves the environment object associated with the current thread.Returns the current name-space.Returns the data model hash.getDateFormatObject(int dateType) getDateFormatObject(int dateType, String pattern) Returns the names of variables directly managed by this scope (i.e.Returns the name of the charset that should be used for URL encoding.List<freemarker.core.ast.TemplateElement>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.Returns a set of variable names that are known at the time of call.getMacroContext(freemarker.core.ast.Macro macro) getMacroNamespace(freemarker.core.ast.Macro macro) Returns the main name-space.getNamespace(String name) Returns the name-space for the name if exists, or null.getNamespaceForPrefix(String prefix) static NumberFormatgetNumberFormatObject(String pattern) getOut()getPrefixForNamespace(String nsURI) Retrieves the currently processed template.Gets a template for importing; used withimportLib(Template importedTemplate, String namespace, boolean global).getTemplateForInclusion(String name, String encoding, boolean parse) Gets a template for inclusion; used withinclude(Template includedTemplate, boolean freshNamespace).getTransform(freemarker.core.ast.Expression exp) getVariable(String name) Returns the variable that is visible in this context.Emulatesimportdirective.Emulatesimportdirective, except thatnamemust be tempate root relative.voidProcesses a Template in the context of thisEnvironment, including its output in theEnvironment's Writer.voidEmulatesincludedirective, except thatnamemust be tempate root relative.booleanisEmpty()keys()voidOutputs the instruction stack.voidprocess()Processes the template to which this environment belongs.voidprocess(LoopContext ictxt) "visit" an IteratorBlockvoidprocess(TemplateNodeModel node, TemplateSequenceModel namespaces) voidput(String varname, TemplateModel value) Set a variable in this scope.Removes a variable in this scope.voidrender(freemarker.core.ast.Macro macro, freemarker.core.ast.ArgsList args, freemarker.core.ast.ParameterList bodyParameters, freemarker.core.ast.TemplateElement nestedBlock) "visit" a macro.voidrender(freemarker.core.ast.TemplateElement element) "Visit" the template element.voidrender(freemarker.core.ast.TemplateElement attemptBlock, freemarker.core.ast.TemplateElement recoveryBlock, List<freemarker.core.parser.ParsingProblem> parsingProblems) Visit a block using buffering/recoveryvoidrender(freemarker.core.ast.TemplateElement element, TemplateDirectiveModel directiveModel, Map<String, TemplateModel> args, List<String> bodyParameterNames) voidrender(freemarker.core.ast.TemplateElement element, TemplateTransformModel transform, Map<String, TemplateModel> args) "Visit" the template element, passing the output through a TemplateTransformModelvoidrender(MacroInvocationBodyContext bctxt) voidrender(TemplateNodeModel node, TemplateSequenceModel namespaces) "Visit" A TemplateNodeModelrenderElementToString(freemarker.core.ast.TemplateElement te) voidrenderSecurely(freemarker.core.ast.TemplateElement element, CodeSource newCodeSource) 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.<T> TrunInScope(Scope scope, TemplateRunnable<T> runnable) voidsets TemplateNodeModel as the current visitor node.voidsetCurriedMacroNamespace(freemarker.core.ast.Macro curriedMacro, freemarker.core.ast.Macro baseMacro) voidsetDateFormat(String formatName) Sets the date format used to convert date models representing date-only dates to strings.voidsetDateTimeFormat(String formatName) Sets the date format used to convert date models representing datetime dates to strings.voidsetGlobalVariable(String name, TemplateModel model) Sets a variable that is visible globally.voidsetLastReturnValue(TemplateModel lastReturnValue) voidSets the locale to assume when searching for template files with no explicit requested locale.voidsetLocalVariable(String name, TemplateModel model) Sets a local variable (one effective only during a macro invocation).voidsetNumberFormat(String formatName) Sets the number format used to convert numbers to strings.voidvoidsetOutputEncoding(String outputEncoding) Sets the output encoding.voidsetTemplateExceptionHandler(TemplateExceptionHandler templateExceptionHandler) Sets the exception handler used to handle template exceptions.voidsetTimeFormat(String formatName) Sets the date format used to convert date models representing time-only values to strings.voidsetTimeZone(TimeZone timeZone) Sets the time zone to use when formatting time values.voidsetURLEscapingCharset(String urlEscapingCharset) Sets the URL escaping charset.voidsetVariable(String name, TemplateModel model) Sets a variable in the current namespace.intsize()voidunqualifiedSet(String name, TemplateModel model) Sets a variable in the most local scope available (corresponds to an unqualified #set instruction)values()voidvisitMacroDef(freemarker.core.ast.Macro macro) Methods inherited from class freemarker.core.Configurable
clone, doAutoImportsAndIncludes, getArithmeticEngine, getBooleanFormat, getBooleanFormat, getCustomAttribute, getCustomAttributeNames, getDateFormat, getDateTimeFormat, getLocale, getNumberFormat, getObjectWrapper, getOutputEncoding, getParent, getSetting, getSettings, getTemplateExceptionHandler, getTimeFormat, getTimeZone, getURLEscapingCharset, invalidSettingValueException, removeCustomAttribute, setArithmeticEngine, setBooleanFormat, setCustomAttribute, setNumbersForComputers, setObjectWrapper, setParent, setSetting, setSettings, setSettings, setStrictBeanModels, unknownSettingException
-
Field Details
-
NULL_WRITER
-
-
Constructor Details
-
Environment
public Environment(Template template, TemplateHashModel rootDataModel, Writer out) throws TemplateException - Throws:
TemplateException
-
-
Method Details
-
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
Retrieves the currently processed template.- Specified by:
getTemplatein interfaceScope- Returns:
- the Template object associated with this Scope.
-
process
Processes the template to which this environment belongs.- Throws:
TemplateExceptionIOException
-
renderSecurely
public void renderSecurely(freemarker.core.ast.TemplateElement element, CodeSource newCodeSource) throws TemplateException, IOException - Throws:
TemplateExceptionIOException
-
render
public void render(freemarker.core.ast.TemplateElement element) throws TemplateException, IOException "Visit" the template element.- Throws:
TemplateExceptionIOException
-
render
public void render(freemarker.core.ast.TemplateElement element, TemplateDirectiveModel directiveModel, Map<String, TemplateModel> args, List<String> bodyParameterNames) throws TemplateException, IOException- Throws:
TemplateExceptionIOException
-
render
public void render(freemarker.core.ast.TemplateElement element, TemplateTransformModel transform, Map<String, TemplateModel> args) throws TemplateException, IOException"Visit" the template element, passing the output through a TemplateTransformModel- Parameters:
element- the element to visit through a transformtransform- the transform to pass the element output throughargs- optional arguments fed to the transform- Throws:
TemplateExceptionIOException
-
render
public void render(freemarker.core.ast.TemplateElement attemptBlock, freemarker.core.ast.TemplateElement recoveryBlock, List<freemarker.core.parser.ParsingProblem> parsingProblems) throws TemplateException, IOException Visit a block using buffering/recovery- Throws:
TemplateExceptionIOException
-
getCurrentRecoveredErrorMessage
- Throws:
TemplateException
-
render
- Throws:
TemplateExceptionIOException
-
process
"visit" an IteratorBlock- Throws:
TemplateExceptionIOException
-
render
public void render(TemplateNodeModel node, TemplateSequenceModel namespaces) throws TemplateException, IOException "Visit" A TemplateNodeModel- Throws:
TemplateExceptionIOException
-
runInScope
public <T> T runInScope(Scope scope, TemplateRunnable<T> runnable) throws TemplateException, IOException - Throws:
TemplateExceptionIOException
-
fallback
- Throws:
TemplateExceptionIOException
-
render
public void render(freemarker.core.ast.Macro macro, freemarker.core.ast.ArgsList args, freemarker.core.ast.ParameterList bodyParameters, freemarker.core.ast.TemplateElement nestedBlock) throws TemplateException, IOException "visit" a macro.- Throws:
TemplateExceptionIOException
-
visitMacroDef
- Throws:
TemplateException
-
getMacroNamespace
-
getMacroContext
-
setCurriedMacroNamespace
public void setCurriedMacroNamespace(freemarker.core.ast.Macro curriedMacro, freemarker.core.ast.Macro baseMacro) -
process
public void process(TemplateNodeModel node, TemplateSequenceModel namespaces) throws TemplateException, IOException - Throws:
TemplateExceptionIOException
-
getCurrentMacroContext
-
setTemplateExceptionHandler
Description copied from class:ConfigurableSets the exception handler used to handle template exceptions.- Overrides:
setTemplateExceptionHandlerin classConfigurable- Parameters:
templateExceptionHandler- the template exception handler to use for handlingTemplateExceptions. By default,TemplateExceptionHandler.HTML_DEBUG_HANDLERis used.
-
setLocale
Description copied from class:ConfigurableSets the locale to assume when searching for template files with no explicit requested locale.- Overrides:
setLocalein classConfigurable
-
setTimeZone
Description copied from class:ConfigurableSets the time zone to use when formatting time values.- Overrides:
setTimeZonein classConfigurable
-
setURLEscapingCharset
Description copied from class:ConfigurableSets the URL escaping charset. Allowsnull, which means that the output encoding will be used for URL escaping.- Overrides:
setURLEscapingCharsetin classConfigurable
-
setOutputEncoding
Description copied from class:ConfigurableSets the output encoding. Allowsnull, which means that the output encoding is not known.- Overrides:
setOutputEncodingin classConfigurable
-
getEffectiveURLEscapingCharset
Returns the name of the charset that should be used for URL encoding. This will benullif the information is not available. The function caches the return value, so it is quick to call it repeately. -
getCollator
-
setOut
-
getOut
-
formatNumber
-
setNumberFormat
Description copied from class:ConfigurableSets the number format used to convert numbers to strings.- Overrides:
setNumberFormatin classConfigurable
-
formatDate
- Throws:
TemplateModelException
-
setTimeFormat
Description copied from class:ConfigurableSets the date format used to convert date models representing time-only values to strings.- Overrides:
setTimeFormatin classConfigurable
-
setDateFormat
Description copied from class:ConfigurableSets the date format used to convert date models representing date-only dates to strings.- Overrides:
setDateFormatin classConfigurable
-
setDateTimeFormat
Description copied from class:ConfigurableSets the date format used to convert date models representing datetime dates to strings.- Overrides:
setDateTimeFormatin classConfigurable
-
getConfiguration
-
getLastReturnValue
-
setLastReturnValue
-
getNumberFormatObject
-
getDateFormatObject
- Throws:
TemplateModelException
-
getDateFormatObject
- Throws:
TemplateModelException
-
getCNumberFormat
Returns theNumberFormatused for the c built-in. This is always US English"0.################", without grouping and without superfluous decimal separator. -
getNewCNumberFormat
-
getTransform
public TemplateTransformModel getTransform(freemarker.core.ast.Expression exp) throws TemplateException - Throws:
TemplateException
-
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- Throws:
TemplateModelException
-
getVariable
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:- An loop variable (if we're in a loop or user defined directive body) such as foo_has_next
- A local variable (if we're in a macro)
- A variable defined in the current namespace (say, via <#assign ...>)
- A variable defined globally (say, via <#global ....>)
- Variable in the data model:
- A variable in the root hash that was exposed to this rendering environment in the Template.process(...) call
- A shared variable set in the configuration via a call to Configuration.setSharedVariable(...)
- Throws:
TemplateModelException
-
get
This method returns a variable from the "global" namespace and falls back to the data model.- 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.
- Throws:
TemplateModelException
-
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.
- Throws:
TemplateModelException
-
setGlobalVariable
Sets a variable that is visible globally. This is correspondent to FTL<#global name=model>. -
setVariable
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
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 variablemodel- the value of the variable.- Throws:
IllegalStateException- if the environment is not executing a macro body.
-
unqualifiedSet
Sets a variable in the most local scope available (corresponds to an unqualified #set instruction)- Parameters:
name- the identifier of the variablemodel- the value of the variable- Throws:
TemplateException
-
getCurrentScope
-
getKnownVariableNames
Returns a set of variable names that are known at the time of call. This includes names of all shared variables in theConfiguration, 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 theTemplateHashModelExinterface, then all names it retrieves through a call toTemplateHashModelEx.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
Outputs the instruction stack. Useful for debugging.TemplateExceptions incorporate this information in their stack traces. -
getEnvironment
- Specified by:
getEnvironmentin interfaceScope- Overrides:
getEnvironmentin classConfigurable- Returns:
- the Environment object associated with this Scope.
-
getEnclosingScope
- Specified by:
getEnclosingScopein interfaceScope- Returns:
- null This 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.)
-
put
Description copied from interface:ScopeSet a variable in this scope. This will typically only be used internally by the FreeMarker engine. -
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
- Specified by:
sizein interfaceTemplateHashModelEx- Returns:
- the number of key/value mappings in the hash.
- Throws:
TemplateModelException
-
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). - Throws:
TemplateModelException
-
values
- Specified by:
valuesin interfaceTemplateHashModelEx- Returns:
- a collection containing the values in the hash.
- Throws:
TemplateModelException
-
getNamespace
Returns the name-space for the name if exists, or null.- Parameters:
name- the template path that you have used with theimportdirective orimportLib(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
Returns the main name-space. This is correspondent of FTL.mainhash. -
getCurrentNamespace
Returns the current name-space. This is correspondent of FTL.namespacehash. -
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
Returns the data model hash. This is correspondent of FTL.datamodelhash. That is, it contains both the variables of the root hash passed to theTemplate.process(...), and the shared variables in theConfiguration. -
getElementStack
-
getCurrentVisitorNode
-
setCurrentVisitorNode
sets TemplateNodeModel as the current visitor node. .current_node -
include
public void include(String name, String encoding, boolean parse) throws IOException, TemplateException Emulatesincludedirective, except thatnamemust 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. -
getTemplateForInclusion
public Template getTemplateForInclusion(String name, String encoding, boolean parse) throws IOException Gets a template for inclusion; used withinclude(Template includedTemplate, boolean freshNamespace). The advantage over simply usingconfig.getTemplate(...)is that it chooses the default encoding as theincludedirective 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 useTemplateCache.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:
IOException
-
include
public void include(Template includedTemplate, boolean freshNamespace) throws TemplateException, IOException Processes a Template in the context of thisEnvironment, including its output in theEnvironment's Writer.- Parameters:
includedTemplate- the template to process. Note that it does not need to be a template returned bygetTemplateForInclusion(String name, String encoding, boolean parse).- Throws:
TemplateExceptionIOException
-
importLib
public TemplateNamespace importLib(String name, String namespace) throws IOException, TemplateException Emulatesimportdirective, except thatnamemust 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. -
getTemplateForImporting
Gets a template for importing; used withimportLib(Template importedTemplate, String namespace, boolean global). The advantage over simply usingconfig.getTemplate(...)is that it chooses the encoding as theimportdirective 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 useTemplateCache.getFullTemplatePath(freemarker.core.Environment, java.lang.String, java.lang.String)to convert paths to template root relative paths.)- Throws:
IOException
-
importLib
public TemplateNamespace importLib(Template loadedTemplate, String namespace, boolean global) throws IOException, TemplateException Emulatesimportdirective.- Parameters:
loadedTemplate- the template to import. Note that it does not need to be a template returned bygetTemplateForImporting(String name).- Throws:
IOExceptionTemplateException
-
renderElementToString
public String renderElementToString(freemarker.core.ast.TemplateElement te) throws IOException, TemplateException - Throws:
IOExceptionTemplateException
-
getNamespaceForPrefix
- Returns:
- the namespace URI registered for this prefix, or null. This is based on the mappings registered in the current namespace.
-
getPrefixForNamespace
-
getDefaultNS
- Returns:
- the default node namespace for the current FTL namespace
-
__getitem__
A hook that Jython uses.- Throws:
TemplateModelException
-
__setitem__
A hook that Jython uses.- Throws:
TemplateException
-