public final class Environment extends Configurable
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)
| Modifier and Type | Class and Description |
|---|---|
class |
Environment.Namespace |
Configurable.SettingValueAssignmentException, Configurable.UnknownSettingExceptionAPI_BUILTIN_ENABLED_KEY, API_BUILTIN_ENABLED_KEY_CAMEL_CASE, API_BUILTIN_ENABLED_KEY_SNAKE_CASE, ARITHMETIC_ENGINE_KEY, ARITHMETIC_ENGINE_KEY_CAMEL_CASE, ARITHMETIC_ENGINE_KEY_SNAKE_CASE, AUTO_FLUSH_KEY, AUTO_FLUSH_KEY_CAMEL_CASE, AUTO_FLUSH_KEY_SNAKE_CASE, AUTO_IMPORT_KEY, AUTO_IMPORT_KEY_CAMEL_CASE, AUTO_IMPORT_KEY_SNAKE_CASE, AUTO_INCLUDE_KEY, AUTO_INCLUDE_KEY_CAMEL_CASE, AUTO_INCLUDE_KEY_SNAKE_CASE, BOOLEAN_FORMAT_KEY, BOOLEAN_FORMAT_KEY_CAMEL_CASE, BOOLEAN_FORMAT_KEY_SNAKE_CASE, CLASSIC_COMPATIBLE_KEY, CLASSIC_COMPATIBLE_KEY_CAMEL_CASE, CLASSIC_COMPATIBLE_KEY_SNAKE_CASE, CUSTOM_DATE_FORMATS_KEY, CUSTOM_DATE_FORMATS_KEY_CAMEL_CASE, CUSTOM_DATE_FORMATS_KEY_SNAKE_CASE, CUSTOM_NUMBER_FORMATS_KEY, CUSTOM_NUMBER_FORMATS_KEY_CAMEL_CASE, CUSTOM_NUMBER_FORMATS_KEY_SNAKE_CASE, DATE_FORMAT_KEY, DATE_FORMAT_KEY_CAMEL_CASE, DATE_FORMAT_KEY_SNAKE_CASE, DATETIME_FORMAT_KEY, DATETIME_FORMAT_KEY_CAMEL_CASE, DATETIME_FORMAT_KEY_SNAKE_CASE, LAZY_AUTO_IMPORTS_KEY, LAZY_AUTO_IMPORTS_KEY_CAMEL_CASE, LAZY_AUTO_IMPORTS_KEY_SNAKE_CASE, LAZY_IMPORTS_KEY, LAZY_IMPORTS_KEY_CAMEL_CASE, LAZY_IMPORTS_KEY_SNAKE_CASE, LOCALE_KEY, LOCALE_KEY_CAMEL_CASE, LOCALE_KEY_SNAKE_CASE, LOG_TEMPLATE_EXCEPTIONS_KEY, LOG_TEMPLATE_EXCEPTIONS_KEY_CAMEL_CASE, LOG_TEMPLATE_EXCEPTIONS_KEY_SNAKE_CASE, NEW_BUILTIN_CLASS_RESOLVER_KEY, NEW_BUILTIN_CLASS_RESOLVER_KEY_CAMEL_CASE, NEW_BUILTIN_CLASS_RESOLVER_KEY_SNAKE_CASE, NUMBER_FORMAT_KEY, NUMBER_FORMAT_KEY_CAMEL_CASE, NUMBER_FORMAT_KEY_SNAKE_CASE, OBJECT_WRAPPER_KEY, OBJECT_WRAPPER_KEY_CAMEL_CASE, OBJECT_WRAPPER_KEY_SNAKE_CASE, OUTPUT_ENCODING_KEY, OUTPUT_ENCODING_KEY_CAMEL_CASE, OUTPUT_ENCODING_KEY_SNAKE_CASE, SHOW_ERROR_TIPS_KEY, SHOW_ERROR_TIPS_KEY_CAMEL_CASE, SHOW_ERROR_TIPS_KEY_SNAKE_CASE, SQL_DATE_AND_TIME_TIME_ZONE_KEY, SQL_DATE_AND_TIME_TIME_ZONE_KEY_CAMEL_CASE, SQL_DATE_AND_TIME_TIME_ZONE_KEY_SNAKE_CASE, STRICT_BEAN_MODELS, STRICT_BEAN_MODELS_KEY, STRICT_BEAN_MODELS_KEY_CAMEL_CASE, STRICT_BEAN_MODELS_KEY_SNAKE_CASE, TEMPLATE_EXCEPTION_HANDLER_KEY, TEMPLATE_EXCEPTION_HANDLER_KEY_CAMEL_CASE, TEMPLATE_EXCEPTION_HANDLER_KEY_SNAKE_CASE, TIME_FORMAT_KEY, TIME_FORMAT_KEY_CAMEL_CASE, TIME_FORMAT_KEY_SNAKE_CASE, TIME_ZONE_KEY, TIME_ZONE_KEY_CAMEL_CASE, TIME_ZONE_KEY_SNAKE_CASE, URL_ESCAPING_CHARSET_KEY, URL_ESCAPING_CHARSET_KEY_CAMEL_CASE, URL_ESCAPING_CHARSET_KEY_SNAKE_CASE| Constructor and Description |
|---|
Environment(Template template,
TemplateHashModel rootDataModel,
Writer out) |
| Modifier and Type | Method and Description |
|---|---|
Object |
__getitem__(String key)
A hook that Jython uses.
|
void |
__setitem__(String key,
Object o)
A hook that Jython uses.
|
boolean |
applyEqualsOperator(TemplateModel leftValue,
TemplateModel rightValue)
Compares two
TemplateModel-s according the rules of the FTL "==" operator. |
boolean |
applyEqualsOperatorLenient(TemplateModel leftValue,
TemplateModel rightValue)
Compares two
TemplateModel-s according the rules of the FTL "==" operator, except that if the two types
are incompatible, they are treated as non-equal instead of throwing an exception. |
boolean |
applyGreaterThanOperator(TemplateModel leftValue,
TemplateModel rightValue)
Compares two
TemplateModel-s according the rules of the FTL ">" operator. |
boolean |
applyLessThanOperator(TemplateModel leftValue,
TemplateModel rightValue)
Compares two
TemplateModel-s according the rules of the FTL "<" operator. |
boolean |
applyLessThanOrEqualsOperator(TemplateModel leftValue,
TemplateModel rightValue)
Compares two
TemplateModel-s according the rules of the FTL "<" operator. |
boolean |
applyWithGreaterThanOrEqualsOperator(TemplateModel leftValue,
TemplateModel rightValue)
Compares two
TemplateModel-s according the rules of the FTL ">=" operator. |
NumberFormat |
getCNumberFormat()
Returns the
NumberFormat used for the c built-in. |
Configuration |
getConfiguration() |
DirectiveCallPlace |
getCurrentDirectiveCallPlace()
Gets the currently executing custom directive's call place information, or
null if there's no
executing custom directive. |
static Environment |
getCurrentEnvironment()
Retrieves the environment object associated with the current thread, or
null if there's no template
processing going on in this thread. |
Environment.Namespace |
getCurrentNamespace()
Returns the current namespace.
|
Template |
getCurrentTemplate()
Returns the
Template that we are "lexically" inside at the moment. |
TemplateNodeModel |
getCurrentVisitorNode() |
Object |
getCustomState(Object identityKey)
Returns the value of a custom state variable, or
null if it's missing; see
setCustomState(Object, Object) for more. |
TemplateHashModel |
getDataModel()
Returns the data-model (also known as the template context in some other template engines).
|
String |
getDefaultNS() |
Environment.Namespace |
getGlobalNamespace()
Returns the name-space that contains the globally visible non-data-model variables (usually created with
<#global ...>). |
TemplateModel |
getGlobalVariable(String name)
Returns the globally visible variable of the given name (or null).
|
TemplateHashModel |
getGlobalVariables()
Returns the read-only hash of globally visible variables.
|
Set |
getKnownVariableNames()
Returns a set of variable names that are known at the time of call.
|
TemplateModel |
getLocalVariable(String name)
Returns the loop or macro local variable corresponding to this variable name.
|
Environment.Namespace |
getMainNamespace()
Returns the main namespace.
|
Template |
getMainTemplate()
Returns the topmost
Template, with other words, the one for which this Environment was created. |
Environment.Namespace |
getNamespace(String name)
Returns the name-space for the name if exists, or null.
|
String |
getNamespaceForPrefix(String prefix) |
Writer |
getOut() |
String |
getPrefixForNamespace(String nsURI) |
Template |
getTemplate()
Deprecated.
Use
getMainTemplate() instead (or getCurrentNamespace() and then
Environment.Namespace.getTemplate()); the value returned by this method is often not what you expect when
it comes to macro/function invocations. |
TemplateDateFormat |
getTemplateDateFormat(int dateType,
Class<? extends Date> dateClass)
Gets a
TemplateDateFormat using the date/time/datetime format settings and the current locale and time
zone. |
TemplateDateFormat |
getTemplateDateFormat(String formatString,
int dateType,
Class<? extends Date> dateClass)
Gets a
TemplateDateFormat for the specified format string and the current locale and time zone. |
TemplateDateFormat |
getTemplateDateFormat(String formatString,
int dateType,
Class<? extends Date> dateClass,
Locale locale)
Like
getTemplateDateFormat(String, int, Class), but allows you to use a different locale than the
current one. |
TemplateDateFormat |
getTemplateDateFormat(String formatString,
int dateType,
Class<? extends Date> dateClass,
Locale locale,
TimeZone timeZone,
TimeZone sqlDateAndTimeTimeZone)
Like
getTemplateDateFormat(String, int, Class), but allows you to use a different locale and time zone
than the current one. |
TemplateDateFormat |
getTemplateDateFormat(String formatString,
int dateType,
Locale locale,
TimeZone timeZone,
boolean zonelessInput)
Gets a
TemplateDateFormat for the specified parameters. |
Template |
getTemplateForImporting(String name)
Gets a template for importing; used with
importLib(Template importedTemplate, String namespace). |
Template |
getTemplateForInclusion(String name,
String encoding,
boolean parse)
Same as
getTemplateForInclusion(String, String, boolean, boolean) with false
ignoreMissing argument. |
Template |
getTemplateForInclusion(String name,
String encoding,
boolean parseAsFTL,
boolean ignoreMissing)
Gets a template for inclusion; used for implementing
include(Template includedTemplate). |
TemplateNumberFormat |
getTemplateNumberFormat()
Returns the current number format (
Configurable.getNumberFormat()) as TemplateNumberFormat. |
TemplateNumberFormat |
getTemplateNumberFormat(String formatString)
Returns the number format as
TemplateNumberFormat for the given format string and the current locale. |
TemplateNumberFormat |
getTemplateNumberFormat(String formatString,
Locale locale)
Returns the number format as
TemplateNumberFormat, for the given format string and locale. |
TemplateModel |
getVariable(String name)
Returns the variable that is visible in this context, or
null if the variable is not found. |
Environment.Namespace |
importLib(String templateName,
String targetNsVarName)
Emulates
import directive, except that templateName must be template root relative. |
Environment.Namespace |
importLib(String templateName,
String targetNsVarName,
boolean lazy)
Like
importLib(String, String), but you can specify if you want a
lazy import or not. |
Environment.Namespace |
importLib(Template loadedTemplate,
String targetNsVarName)
Does what the
#import directive does, but with an already loaded template. |
void |
include(String name,
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. |
boolean |
isInAttemptBlock()
Tells if we are inside an #attempt block (but before #recover).
|
void |
outputInstructionStack(PrintWriter pw)
Prints the current FTL stack trace.
|
void |
process()
Processes the template to which this environment belongs to.
|
void |
setCurrentVisitorNode(TemplateNodeModel node)
sets TemplateNodeModel as the current visitor node.
|
Object |
setCustomState(Object identityKey,
Object value)
Sets the value of a custom state variable.
|
void |
setDateFormat(String dateFormat)
Sets the format used to convert
Date-s to string-s that are date (no time part) values,
also the format that someString?date will use to parse strings. |
void |
setDateTimeFormat(String dateTimeFormat)
Sets the format used to convert
Date-s to string-s that are date-time (timestamp) values,
also the format that someString?datetime will use to parse strings. |
void |
setGlobalVariable(String name,
TemplateModel model)
Sets a variable that is visible globally.
|
void |
setLocale(Locale locale)
Sets the default locale used for number and date formatting (among others), also the locale used for searching
localized template variations when no locale was explicitly requested.
|
void |
setLocalVariable(String name,
TemplateModel model)
Sets a local variable (one effective only during a macro invocation).
|
void |
setNumberFormat(String formatName)
Sets the default number format used to convert numbers to strings.
|
void |
setOut(Writer out) |
void |
setOutputEncoding(String outputEncoding)
Informs FreeMarker about the charset used for the output.
|
void |
setSQLDateAndTimeTimeZone(TimeZone timeZone)
Sets the time zone used when dealing with
java.sql.Date and
java.sql.Time values. |
void |
setTemplateExceptionHandler(TemplateExceptionHandler templateExceptionHandler)
Sets the exception handler used to handle exceptions occurring inside templates.
|
void |
setTimeFormat(String timeFormat)
Sets the format used to convert
Date-s to string-s that are time (no date part) values,
also the format that someString?time will use to parse strings. |
void |
setTimeZone(TimeZone timeZone)
Sets the time zone to use when formatting date/time values.
|
void |
setURLEscapingCharset(String urlEscapingCharset)
Sets the URL escaping charset.
|
void |
setVariable(String name,
TemplateModel model)
Sets a variable in the current namespace.
|
String |
toFullTemplateName(String baseName,
String targetName)
Resolves a reference to a template (like the one used in
#include or #import), assuming a base
name. |
void |
visit(freemarker.core.TemplateElement element,
TemplateDirectiveModel directiveModel,
Map args,
List bodyParameterNames)
Deprecated.
Should be internal API
|
addAutoImport, addAutoInclude, clone, doAutoImportsAndIncludes, getArithmeticEngine, getAutoFlush, getAutoImports, getAutoImportsWithoutFallback, getAutoIncludes, getAutoIncludesWithoutFallback, getBooleanFormat, getClassicCompatibleAsInt, getCorrectedNameForUnknownSetting, getCustomAttribute, getCustomAttributeNames, getCustomDateFormat, getCustomDateFormats, getCustomDateFormatsWithoutFallback, getCustomNumberFormat, getCustomNumberFormats, getCustomNumberFormatsWithoutFallback, getDateFormat, getDateTimeFormat, getEnvironment, getLazyAutoImports, getLazyImports, getLocale, getLogTemplateExceptions, getNewBuiltinClassResolver, getNumberFormat, getObjectWrapper, getOutputEncoding, getParent, getSetting, getSettingNames, getSettings, getShowErrorTips, getSQLDateAndTimeTimeZone, getTemplateExceptionHandler, getTimeFormat, getTimeZone, getURLEscapingCharset, hasCustomFormats, invalidSettingValueException, isAPIBuiltinEnabled, isAPIBuiltinEnabledSet, isArithmeticEngineSet, isAutoFlushSet, isAutoImportsSet, isAutoIncludesSet, isBooleanFormatSet, isClassicCompatible, isClassicCompatibleSet, isCustomDateFormatsSet, isCustomNumberFormatsSet, isDateFormatSet, isDateTimeFormatSet, isLazyAutoImportsSet, isLazyImportsSet, isLocaleSet, isLogTemplateExceptionsSet, isNewBuiltinClassResolverSet, isNumberFormatSet, isObjectWrapperSet, isOutputEncodingSet, isShowErrorTipsSet, isSQLDateAndTimeTimeZoneSet, isTemplateExceptionHandlerSet, isTimeFormatSet, isTimeZoneSet, isURLEscapingCharsetSet, parseAsImportList, parseAsList, parseAsSegmentedList, removeAutoImport, removeAutoInclude, removeCustomAttribute, setAPIBuiltinEnabled, setArithmeticEngine, setAutoFlush, setAutoImports, setAutoIncludes, setBooleanFormat, setClassicCompatible, setClassicCompatibleAsInt, setCustomAttribute, setCustomDateFormats, setCustomNumberFormats, setLazyAutoImports, setLazyImports, setLogTemplateExceptions, setNewBuiltinClassResolver, setObjectWrapper, setSetting, setSettings, setSettings, setShowErrorTips, setStrictBeanModels, settingValueAssignmentException, unknownSettingExceptionpublic Environment(Template template, TemplateHashModel rootDataModel, Writer out)
public static Environment getCurrentEnvironment()
null if there's no template
processing going on in this 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.@Deprecated public Template getTemplate()
getMainTemplate() instead (or getCurrentNamespace() and then
Environment.Namespace.getTemplate()); the value returned by this method is often not what you expect when
it comes to macro/function invocations.Configurable.getParent(). If Configuration.getIncompatibleImprovements() is
at least 2.3.22, then that will be the same as getMainTemplate(). Otherwise the returned value follows
the Environment parent switchings that occur at #include/#import and #nested
directive calls, that is, it's not very meaningful outside FreeMarker internals.public Template getMainTemplate()
Template, with other words, the one for which this Environment was created.
That template will never change, like #include or macro calls don't change it.getCurrentNamespace()public Template getCurrentTemplate()
Template that we are "lexically" inside at the moment. This template will change when
entering an #include or calling a macro or function in another template, or returning to yet another
template with #nested. As such, it's useful in TemplateDirectiveModel to find out if from where
the directive was called from.getMainTemplate(),
getCurrentNamespace()public DirectiveCallPlace getCurrentDirectiveCallPlace()
null if there's no
executing custom directive. This currently only works for calls made from templates with the <@...>
syntax. This should only be called from the TemplateDirectiveModel that was invoked with <@...>,
otherwise its return value is not defined by this API (it's usually null).public void process()
throws TemplateException,
IOException
TemplateExceptionIOException@Deprecated public void visit(freemarker.core.TemplateElement element, TemplateDirectiveModel directiveModel, Map args, List bodyParameterNames) throws TemplateException, IOException
TemplateExceptionIOExceptionpublic boolean isInAttemptBlock()
TemplateExceptionHandler-s, as then they may don't want to print the error to the output, as
#attempt will roll it back anyway.public void setTemplateExceptionHandler(TemplateExceptionHandler templateExceptionHandler)
ConfigurableTemplateExceptionHandler.DEBUG_HANDLER. The recommended values are:
TemplateExceptionHandler.RETHROW_HANDLER
TemplateExceptionHandler.HTML_DEBUG_HANDLER
TemplateExceptionHandler.DEBUG_HANDLER
All of these will let the exception propagate further, so that you can catch it around
Template.process(Object, Writer) for example. The difference is in what they print on the output before
they do that.
Note that the TemplateExceptionHandler is not meant to be used for generating HTTP error pages.
Neither is it meant to be used to roll back the printed output. These should be solved outside template
processing when the exception raises from Template.process.
TemplateExceptionHandler meant to be used if you want to include special content in the template
output, or if you want to suppress certain exceptions.
setTemplateExceptionHandler in class Configurablepublic void setLocale(Locale locale)
ConfigurablesetLocale in class ConfigurableConfiguration.getTemplate(String, Locale)public void setTimeZone(TimeZone timeZone)
ConfigurableTimeZone.getDefault()), regardless of the "locale" FreeMarker setting,
so in a server application you probably want to set it explicitly in the Environment to match the
preferred time zone of target audience (like the Web page visitor).
If you or the templates set the time zone, you should probably also set
Configurable.setSQLDateAndTimeTimeZone(TimeZone)!
setTimeZone in class ConfigurableConfigurable.setSQLDateAndTimeTimeZone(TimeZone)public void setSQLDateAndTimeTimeZone(TimeZone timeZone)
Configurablejava.sql.Date and
java.sql.Time values. It defaults to null for backward compatibility, but in most
application this should be set to the JVM default time zone (server default time zone), because that's what
most JDBC drivers will use when constructing the java.sql.Date and
java.sql.Time values. If this setting is null, FreeMarker will use the value of
(Configurable.getTimeZone()) for java.sql.Date and java.sql.Time values,
which often gives bad results.
This setting doesn't influence the formatting of other kind of values (like of
java.sql.Timestamp or plain java.util.Date values).
To decide what value you need, a few things has to be understood:
Date and its subclasses store (milliseconds since
the epoch). Obviously, this is impossible to do. So JDBC just chooses a physical time which, when rendered
with the JVM default time zone, will give the same field values as those stored
in the database. (Actually, you can give JDBC a calendar, and so it can use other time zones too, but most
application won't care using those overloads.) For example, assume that the system time zone is GMT+02:00.
Then, 2014-07-12 in the database will be translated to physical time 2014-07-11 22:00:00 UTC, because that
rendered in GMT+02:00 gives 2014-07-12 00:00:00. Similarly, 11:57:00 in the database will be translated to
physical time 1970-01-01 09:57:00 UTC. Thus, the physical time stored in the returned value depends on the
default system time zone of the JDBC client, not just on the content in the database. (This used to be the
default behavior of ORM-s, like Hibernate, too.)
time_zone FreeMarker configuration setting sets the time zone used for the
template output. For example, when a web page visitor has a preferred time zone, the web application framework
may calls setTimeZone(TimeZone) with that time zone. Thus, the visitor will
see java.sql.Timestamp and plain java.util.Date values as
they look in his own time zone. While
this is desirable for those types, as they meant to represent physical points on the time line, this is not
necessarily desirable for date-only and time-only values. When sql_date_and_time_time_zone is
null, time_zone is used for rendering all kind of date/time/dateTime values, including
java.sql.Date and java.sql.Time, and then if, for example,
time_zone is GMT+00:00, the
values from the earlier examples will be shown as 2014-07-11 (one day off) and 09:57:00 (2 hours off). While
those are the time zone correct renderings, those values probably was meant to shown "as is".
java.sql.Timestamp too. FreeMarker assumes that you have set up your
application so that time stamps coming from the database go through the necessary conversion to store the
correct distance from the epoch (1970-01-01 00:00:00 UTC), as requested by Date. In that case
the time stamp can be safely rendered in different time zones, and thus it needs no special treatment.
setSQLDateAndTimeTimeZone in class ConfigurabletimeZone - Maybe null, in which case java.sql.Date and
java.sql.Time values will be formatted in the time zone returned by
Configurable.getTimeZone().
(Note that since null is an allowed value for this setting, it will not cause
Configurable.getSQLDateAndTimeTimeZone() to fall back to the parent configuration.)Configurable.setTimeZone(TimeZone)public void setURLEscapingCharset(String urlEscapingCharset)
Configurablenull), the output encoding
(Configurable.setOutputEncoding(String)) will be used for URL escaping.
Defaults to null.setURLEscapingCharset in class Configurablepublic void setOutputEncoding(String outputEncoding)
Configurablenull means that the output encoding is not known.
Defaults to null (unknown).
setOutputEncoding in class Configurablepublic boolean applyEqualsOperator(TemplateModel leftValue, TemplateModel rightValue) throws TemplateException
TemplateModel-s according the rules of the FTL "==" operator.TemplateExceptionpublic boolean applyEqualsOperatorLenient(TemplateModel leftValue, TemplateModel rightValue) throws TemplateException
TemplateModel-s according the rules of the FTL "==" operator, except that if the two types
are incompatible, they are treated as non-equal instead of throwing an exception. Comparing dates of different
types (date-only VS time-only VS date-time) will still throw an exception, however.TemplateExceptionpublic boolean applyLessThanOperator(TemplateModel leftValue, TemplateModel rightValue) throws TemplateException
TemplateModel-s according the rules of the FTL "<" operator.TemplateExceptionpublic boolean applyLessThanOrEqualsOperator(TemplateModel leftValue, TemplateModel rightValue) throws TemplateException
TemplateModel-s according the rules of the FTL "<" operator.TemplateExceptionpublic boolean applyGreaterThanOperator(TemplateModel leftValue, TemplateModel rightValue) throws TemplateException
TemplateModel-s according the rules of the FTL ">" operator.TemplateExceptionpublic boolean applyWithGreaterThanOrEqualsOperator(TemplateModel leftValue, TemplateModel rightValue) throws TemplateException
TemplateModel-s according the rules of the FTL ">=" operator.TemplateExceptionpublic void setOut(Writer out)
public Writer getOut()
public void setNumberFormat(String formatName)
Configurable"number": The number format returned by NumberFormat.getNumberInstance(Locale)"currency": The number format returned by NumberFormat.getCurrencyInstance(Locale)"percent": The number format returned by NumberFormat.getPercentInstance(Locale)"computer": The number format used by FTL's c built-in (like in someNumber?c).DecimalFormat pattern (like "0.##"). This syntax has a FreeMarker-specific
extension, so that you can specify options like the rounding mode and the symbols used in this string. For
example, ",000;; roundingMode=halfUp groupingSeparator=_" will format numbers like ",000"
would, but with half-up rounding mode, and _ as the group separator. See more about "extended Java
decimal format" in the FreeMarker Manual.
@ character followed by a letter then it's interpreted as a custom number
format, but only if either Configuration.getIncompatibleImprovements() is at least 2.3.24, or
there's any custom formats defined (even if custom date/time/dateTime format). The format of a such string
is "@name" or "@name parameters", where
name is the key in the Map set by Configurable.setCustomNumberFormats(Map), and
parameters is parsed by the custom TemplateNumberFormat.
Defaults to "number".
setNumberFormat in class Configurablepublic TemplateNumberFormat getTemplateNumberFormat() throws TemplateValueFormatException
Configurable.getNumberFormat()) as TemplateNumberFormat.
Performance notes: The result is stored for reuse, so calling this method frequently is usually not a problem.
However, at least as of this writing (2.3.24), changing the current locale setLocale(Locale) or changing
the current number format (setNumberFormat(String)) will drop the stored value, so it will have to be
recalculated.
TemplateValueFormatExceptionpublic TemplateNumberFormat getTemplateNumberFormat(String formatString) throws TemplateValueFormatException
TemplateNumberFormat for the given format string and the current locale.
(The current locale is the locale returned by Configurable.getLocale().) Note that the result will be cached in the
Environment instance (though at least in 2.3.24 the cache will be flushed if the current locale of the
Environment is changed).formatString - A string that you could also use as the value of the numberFormat configuration setting. Can't
be null.TemplateValueFormatExceptionpublic TemplateNumberFormat getTemplateNumberFormat(String formatString, Locale locale) throws TemplateValueFormatException
TemplateNumberFormat, for the given format string and locale. To get a
number format for the current locale, use getTemplateNumberFormat(String) instead.
Note on performance (which was true at least for 2.3.24): Unless the locale happens to be equal to the current
locale, the Environment-level format cache can't be used, so the format string has to be parsed and the
matching factory has to be get an invoked, which is much more expensive than getting the format from the cache.
Thus the returned format should be stored by the caller for later reuse (but only within the current thread and
in relation to the current Environment), if it will be needed frequently.
formatString - A string that you could also use as the value of the numberFormat configuration setting.locale - The locale of the number format; not null.TemplateValueFormatExceptionpublic NumberFormat getCNumberFormat()
NumberFormat used for the c built-in. This is always US English
"0.################", without grouping and without superfluous decimal separator.public void setTimeFormat(String timeFormat)
ConfigurableDate-s to string-s that are time (no date part) values,
also the format that someString?time will use to parse strings.
For the possible values see Configurable.setDateTimeFormat(String).
Defaults to "", which means "use the FreeMarker default", which is currently "medium".
setTimeFormat in class Configurablepublic void setDateFormat(String dateFormat)
ConfigurableDate-s to string-s that are date (no time part) values,
also the format that someString?date will use to parse strings.
For the possible values see Configurable.setDateTimeFormat(String).
Defaults to "", which means "use the FreeMarker default", which is currently "medium".
setDateFormat in class Configurablepublic void setDateTimeFormat(String dateTimeFormat)
ConfigurableDate-s to string-s that are date-time (timestamp) values,
also the format that someString?datetime will use to parse strings.
The possible setting values are (the quotation marks aren't part of the value itself):
Patterns accepted by Java's SimpleDateFormat, for example "dd.MM.yyyy HH:mm:ss" (where
HH means 24 hours format) or "MM/dd/yyyy hh:mm:ss a" (where a prints AM or PM, if
the current language is English).
"xs" for XML Schema format, or "iso" for ISO 8601:2004 format.
These formats allow various additional options, separated with space, like in
"iso m nz" (or with _, like in "iso_m_nz"; this is useful in a case like
lastModified?string.iso_m_nz). The options and their meanings are:
Accuracy options:
ms = Milliseconds, always shown with all 3 digits, even if it's all 0-s.
Example: 13:45:05.800
s = Seconds (fraction seconds are dropped even if non-0), like 13:45:05
m = Minutes, like 13:45. This isn't allowed for "xs".
h = Hours, like 13. This isn't allowed for "xs".
Neither = Up to millisecond accuracy, but trailing millisecond 0-s are removed, also the whole
milliseconds part if it would be 0 otherwise. Example: 13:45:05.8
Time zone offset visibility options:
fz = "Force Zone", always show time zone offset (even for for
java.sql.Date and java.sql.Time values).
But, because ISO 8601 doesn't allow for dates (means date without time of the day) to
show the zone offset, this option will have no effect in the case of "iso" with
dates.
nz = "No Zone", never show time zone offset
Neither = always show time zone offset, except for java.sql.Date
and java.sql.Time, and for "iso" date values.
Time zone options:
u = Use UTC instead of what the time_zone setting suggests. However,
java.sql.Date and java.sql.Time aren't affected
by this (see Configurable.setSQLDateAndTimeTimeZone(TimeZone) to understand why)
fu = "Force UTC", that is, use UTC instead of what the time_zone or the
sql_date_and_time_time_zone setting suggests. This also effects
java.sql.Date and java.sql.Time values
Neither = Use the time zone suggested by the time_zone or the
sql_date_and_time_time_zone configuration setting (Configurable.setTimeZone(TimeZone) and
Configurable.setSQLDateAndTimeTimeZone(TimeZone)).
The options can be specified in any order.
Options from the same category are mutually exclusive, like using m and s
together is an error.
The accuracy and time zone offset visibility options don't influence parsing, only formatting. For example, even if you use "iso m nz", "2012-01-01T15:30:05.125+01" will be parsed successfully and with milliseconds accuracy. The time zone options (like "u") influence what time zone is chosen only when parsing a string that doesn't contain time zone offset.
Parsing with "iso" understands both extend format and basic format, like
20141225T235018. It doesn't, however, support the parsing of all kind of ISO 8601 strings: if
there's a date part, it must use year, month and day of the month values (not week of the year), and the
day can't be omitted.
The output of "iso" is deliberately so that it's also a good representation of the value with
XML Schema format, except for 0 and negative years, where it's impossible. Also note that the time zone
offset is omitted for date values in the "iso" format, while it's preserved for the "xs"
format.
"short", "medium", "long", or "full", which that has locale-dependent
meaning defined by the Java platform (see in the documentation of DateFormat).
For date-time values, you can specify the length of the date and time part independently, be separating
them with _, like "short_medium". ("medium" means
"medium_medium" for date-time values.)
Anything that starts with "@" followed by a letter is interpreted as a custom
date/time/dateTime format, but only if either Configuration.getIncompatibleImprovements()
is at least 2.3.24, or there's any custom formats defined (even if custom number format). The format of
such string is "@name" or "@name parameters", where
name is the key in the Map set by Configurable.setCustomDateFormats(Map), and
parameters is parsed by the custom number format.
Defaults to "", which means "use the FreeMarker default", which is currently "medium_medium".
setDateTimeFormat in class Configurablepublic Configuration getConfiguration()
public TemplateDateFormat getTemplateDateFormat(int dateType, Class<? extends Date> dateClass) throws TemplateValueFormatException
TemplateDateFormat using the date/time/datetime format settings and the current locale and time
zone. (The current locale is the locale returned by Configurable.getLocale(). The current time zone is
Configurable.getTimeZone() or Configurable.getSQLDateAndTimeTimeZone()).dateType - The FTL date type; see the similar parameter of
TemplateDateFormatFactory.get(String, int, Locale, TimeZone, boolean, Environment)dateClass - The exact Date class, like Date or Time; this can influences
time zone selection. See also: setSQLDateAndTimeTimeZone(TimeZone)TemplateValueFormatExceptionpublic TemplateDateFormat getTemplateDateFormat(String formatString, int dateType, Class<? extends Date> dateClass) throws TemplateValueFormatException
TemplateDateFormat for the specified format string and the current locale and time zone. (The
current locale is the locale returned by Configurable.getLocale(). The current time zone is Configurable.getTimeZone() or
Configurable.getSQLDateAndTimeTimeZone()).
Note on performance: The result will be cached in the Environment instance. However, at least in 2.3.24
the cached entries that depend on the current locale or the current time zone or the current date/time/datetime
format of the Environment will be lost when those settings are changed.
formatString - Like "iso m" or "dd.MM.yyyy HH:mm" or "@somethingCustom" or
"@somethingCustom params"TemplateValueFormatExceptionpublic TemplateDateFormat getTemplateDateFormat(String formatString, int dateType, Class<? extends Date> dateClass, Locale locale) throws TemplateValueFormatException
getTemplateDateFormat(String, int, Class), but allows you to use a different locale than the
current one. If you want to use the current locale, use getTemplateDateFormat(String, int, Class)
instead.
Performance notes regarding the locale and time zone parameters of
getTemplateDateFormat(String, int, Locale, TimeZone, boolean) apply.
locale - Can't be null; See the similar parameter of
TemplateDateFormatFactory.get(String, int, Locale, TimeZone, boolean, Environment)TemplateValueFormatExceptiongetTemplateDateFormat(String, int, Class)public TemplateDateFormat getTemplateDateFormat(String formatString, int dateType, Class<? extends Date> dateClass, Locale locale, TimeZone timeZone, TimeZone sqlDateAndTimeTimeZone) throws TemplateValueFormatException
getTemplateDateFormat(String, int, Class), but allows you to use a different locale and time zone
than the current one. If you want to use the current locale and time zone, use
getTemplateDateFormat(String, int, Class) instead.
Performance notes regarding the locale and time zone parameters of
getTemplateDateFormat(String, int, Locale, TimeZone, boolean) apply.
timeZone - The TimeZone used if dateClass is not an SQL date-only or time-only type. Can't be
null.sqlDateAndTimeTimeZone - The TimeZone used if dateClass is an SQL date-only or time-only type. Can't be
null.TemplateValueFormatExceptiongetTemplateDateFormat(String, int, Class)public TemplateDateFormat getTemplateDateFormat(String formatString, int dateType, Locale locale, TimeZone timeZone, boolean zonelessInput) throws TemplateValueFormatException
TemplateDateFormat for the specified parameters. This is mostly meant to be used by
TemplateDateFormatFactory implementations to delegate to a format based on a specific format string. It
works well for that, as its parameters are the same low level values as the parameters of
TemplateDateFormatFactory.get(String, int, Locale, TimeZone, boolean, Environment). For other tasks
consider the other overloads of this method.
Note on performance (which was true at least for 2.3.24): Unless the locale happens to be equal to the current
locale and the time zone with one of the current time zones (Configurable.getTimeZone() or
Configurable.getSQLDateAndTimeTimeZone()), the Environment-level format cache can't be used, so the format
string has to be parsed and the matching factory has to be get an invoked, which is much more expensive than
getting the format from the cache. Thus the returned format should be stored by the caller for later reuse (but
only within the current thread and in relation to the current Environment), if it will be needed
frequently.
formatString - Like "iso m" or "dd.MM.yyyy HH:mm" or "@somethingCustom" or
"@somethingCustom params"dateType - The FTL date type; see the similar parameter of
TemplateDateFormatFactory.get(String, int, Locale, TimeZone, boolean, Environment)timeZone - Not null; See the similar parameter of
TemplateDateFormatFactory.get(String, int, Locale, TimeZone, boolean, Environment)locale - Not null; See the similar parameter of
TemplateDateFormatFactory.get(String, int, Locale, TimeZone, boolean, Environment)zonelessInput - See the similar parameter of
TemplateDateFormatFactory.get(String, int, Locale, TimeZone, boolean, Environment)TemplateValueFormatExceptionpublic TemplateModel getLocalVariable(String name) throws TemplateModelException
TemplateModelExceptionpublic TemplateModel getVariable(String name) throws TemplateModelException
null if the variable is not found. This is the
correspondent to an FTL top-level variable reading expression. That is, it tries to find the the variable in this
order:
TemplateModelExceptionpublic TemplateModel getGlobalVariable(String name) throws TemplateModelException
.globals.name. This will first look at variables that were assigned globally via: <#global
...> and then at the data model exposed to the template.TemplateModelExceptionpublic void setGlobalVariable(String name, TemplateModel model)
<#global name=model>. This can be considered a convenient shorthand for:
getGlobalNamespace().put(name, model)public void setVariable(String name, TemplateModel model)
<#assign name=model>. This can be considered a convenient shorthand for:
getCurrentNamespace().put(name, model)public void setLocalVariable(String name, TemplateModel model)
<#local name=model>.name - the identifier of the variablemodel - the value of the variable.IllegalStateException - if the environment is not executing a macro body.public Set getKnownVariableNames() throws TemplateModelException
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.TemplateModelExceptionpublic void outputInstructionStack(PrintWriter pw)
TemplateExceptions incorporate this information
in their stack traces.public Environment.Namespace getNamespace(String name)
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.public Environment.Namespace getMainNamespace()
.main hash.public Environment.Namespace getCurrentNamespace()
.namespace hash. Initially, the current name
space is the main namespace, but when inside an #import-ed template, it will change to the namespace of
that import. Note that #include doesn't affect the namespace, so if you are in an #import-ed
template and then from there do an #include, the current namespace will remain the namespace of the
#import.public Environment.Namespace getGlobalNamespace()
<#global ...>).public TemplateHashModel getDataModel()
public TemplateHashModel getGlobalVariables()
.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.public TemplateNodeModel getCurrentVisitorNode()
public void setCurrentVisitorNode(TemplateNodeModel node)
public void include(String name, String encoding, boolean parse) throws IOException, TemplateException
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.
public Template getTemplateForInclusion(String name, String encoding, boolean parse) throws IOException
getTemplateForInclusion(String, String, boolean, boolean) with false
ignoreMissing argument.IOExceptionpublic Template getTemplateForInclusion(String name, String encoding, boolean parseAsFTL, boolean ignoreMissing) throws IOException
include(Template includedTemplate). The advantage
over simply using config.getTemplate(...) is that it chooses the default encoding exactly as the
include directive does, although that encoding selection mechanism is a historical baggage and
considered to be harmful.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.) For more details see the identical parameter of
Configuration.getTemplate(String, Locale, String, boolean, boolean)encoding - the charset of the obtained template. If null, the encoding of the top template that is
currently being processed in this Environment is used, which can lead to odd situations, so
using null is not recommended. In most applications, the value of
Configuration.getEncoding(Locale) (or Configuration.getDefaultEncoding()) should be
used here.parseAsFTL - See identical parameter of Configuration.getTemplate(String, Locale, String, boolean, boolean)ignoreMissing - See identical parameter of Configuration.getTemplate(String, Locale, String, boolean, boolean)Configuration.getTemplate(String, Locale, String, boolean, boolean)IOException - Same as exceptions thrown by
Configuration.getTemplate(String, Locale, String, boolean, boolean)public void include(Template includedTemplate) throws TemplateException, IOException
Environment, including its output in the
Environment's Writer.includedTemplate - the template to process. Note that it does not need to be a template returned by
getTemplateForInclusion(String name, String encoding, boolean parse).TemplateExceptionIOExceptionpublic Environment.Namespace importLib(String templateName, String targetNsVarName) throws IOException, TemplateException
import directive, except that templateName must be template root relative.
It's the same as importLib(getTemplateForImporting(templateName), 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.
If it will be a lazy or an eager import is decided by the value of Configurable.getLazyImports(). You
can also directly control that aspect by using importLib(String, String, boolean) instead.
null. This is possibly a lazily self-initializing namespace, which means that it will only
try to get and process the imported template when you access its content.IOExceptionTemplateExceptiongetTemplateForImporting(String templateName),
importLib(Template includedTemplate, String namespaceVarName),
importLib(String, String, boolean)public Environment.Namespace importLib(Template loadedTemplate, String targetNsVarName) throws IOException, TemplateException
#import directive does, but with an already loaded template.loadedTemplate - The template to import. Note that it does not need to be a template returned by
getTemplateForImporting(String name).targetNsVarName - The name of the FTL variable that will store the namespace.IOExceptionTemplateExceptiongetTemplateForImporting(String name),
importLib(Template includedTemplate, String namespaceVarName)public Environment.Namespace importLib(String templateName, String targetNsVarName, boolean lazy) throws IOException, TemplateException
importLib(String, String), but you can specify if you want a
lazy import or not.null. This is possibly a lazily self-initializing namespace, which mean that it will only try
to get and process the imported template when you access its content.IOExceptionTemplateExceptionpublic Template getTemplateForImporting(String name) throws IOException
importLib(Template importedTemplate, String namespace). The
advantage over simply using config.getTemplate(...) is that it chooses the encoding as the
import directive does.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.)IOExceptionpublic String toFullTemplateName(String baseName, String targetName) throws MalformedTemplateNameException
#include or #import), assuming a base
name. This gives a full (that is, absolute), even if non-normalized template name, that could be used for
Configuration.getTemplate(String). This is mostly used when a
template refers to another template.baseName - The name to which relative targetName-s are relative to. Maybe null, which usually
means that the base is the root "directory". Assuming TemplateNameFormat.DEFAULT_2_3_0 or
TemplateNameFormat.DEFAULT_2_4_0, the rules are as follows. If you want to specify a base
directory here, it must end with "/". If it doesn't end with "/", it's parent
directory will be used as the base path. Might starts with a scheme part (like "foo://", or
with TemplateNameFormat.DEFAULT_2_4_0 even just "foo:").targetName - The name of the template, which is either a relative or absolute name. Assuming
TemplateNameFormat.DEFAULT_2_3_0 or TemplateNameFormat.DEFAULT_2_4_0, the rules are as
follows. If it starts with "/" or contains a scheme part separator ("://", also, with
TemplateNameFormat.DEFAULT_2_4_0 a ":" with no "/" anywhere before it) then
it's an absolute name, otherwise it's a relative path. Relative paths are interpreted relatively to
the baseName. Absolute names are simply returned as is, ignoring the baseName, except,
when the baseName has scheme part while the targetName doesn't have, then the schema
of the baseName is prepended to the targetName.MalformedTemplateNameExceptionpublic String getNamespaceForPrefix(String prefix)
public String getDefaultNS()
public Object __getitem__(String key) throws TemplateModelException
TemplateModelExceptionpublic void __setitem__(String key, Object o) throws TemplateException
TemplateExceptionpublic Object getCustomState(Object identityKey)
null if it's missing; see
setCustomState(Object, Object) for more.public Object setCustomState(Object identityKey, Object value)
TemplateNumberFormatFactory-es, TemplateDateFormatFactory-es, and similar user-implementable,
pluggable objects, which want to maintain an Environment-scoped state (such as a cache).identityKey - The key that identifies the variable, by its object identity (not by Object.equals(Object)).
This should be something like a private static final Object CUSTOM_STATE_KEY = new Object();
in the class that needs this state variable.value - The value of the variable. Can be anything, even null.null if the variable didn't exist.