Class Template
- java.lang.Object
-
- freemarker.core.Configurable
-
- freemarker.template.Template
-
public class Template extends Configurable
Stores an already parsed template, ready to be processed (rendered) for unlimited times, possibly from multiple threads.Typically, you will use
Configuration.getTemplate(String)
to create/getTemplate
objects, so you don't construct them directly. But you can also construct a template from aReader
or aString
that contains the template source code. But then it's important to know that while the resultingTemplate
is efficient for later processing, creating a newTemplate
itself is relatively expensive. So try to re-useTemplate
objects if possible.Configuration.getTemplate(String)
(and its overloads) does that (cachingTemplate
-s) for you, but the constructor of course doesn't, so it's up to you to solve then.Objects of this class meant to be handled as immutable and thus thread-safe. However, it has some setter methods for changing FreeMarker settings. Those must not be used while the template is being processed, or if the template object is already accessible from multiple threads. If some templates need different settings that those coming from the shared
Configuration
, and you are usingConfiguration.getTemplate(String)
(or its overloads), then useConfiguration.setTemplateConfigurations(freemarker.cache.TemplateConfigurationFactory)
to achieve that.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
Template.WrongEncodingException
Thrown by theTemplate
constructors that specify a non-null
encoding whoch doesn't match the encoding specified in the#ftl
header of the template.-
Nested classes/interfaces inherited from class freemarker.core.Configurable
Configurable.SettingValueAssignmentException, Configurable.UnknownSettingException
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.String
DEFAULT_NAMESPACE_PREFIX
static java.lang.String
NO_NS_PREFIX
-
Fields inherited from class freemarker.core.Configurable
API_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, ATTEMPT_EXCEPTION_REPORTER_KEY, ATTEMPT_EXCEPTION_REPORTER_KEY_CAMEL_CASE, ATTEMPT_EXCEPTION_REPORTER_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, TRUNCATE_BUILTIN_ALGORITHM_KEY, TRUNCATE_BUILTIN_ALGORITHM_KEY_CAMEL_CASE, TRUNCATE_BUILTIN_ALGORITHM_KEY_SNAKE_CASE, URL_ESCAPING_CHARSET_KEY, URL_ESCAPING_CHARSET_KEY_CAMEL_CASE, URL_ESCAPING_CHARSET_KEY_SNAKE_CASE, WRAP_UNCHECKED_EXCEPTIONS_KEY, WRAP_UNCHECKED_EXCEPTIONS_KEY_CAMEL_CASE, WRAP_UNCHECKED_EXCEPTIONS_KEY_SNAKE_CASE
-
-
Constructor Summary
Constructors Constructor Description Template(java.lang.String name, java.io.Reader reader)
Deprecated.This constructor uses the "default"Configuration
instance, which can easily lead to erroneous, unpredictable behavior.Template(java.lang.String name, java.io.Reader reader, Configuration cfg)
Template(java.lang.String name, java.io.Reader reader, Configuration cfg, java.lang.String encoding)
Convenience constructor forTemplate(name, null, reader, cfg, encoding)
.Template(java.lang.String name, java.lang.String sourceCode, Configuration cfg)
Convenience constructor forTemplate(name, new StringReader(reader), cfg)
.Template(java.lang.String name, java.lang.String sourceName, java.io.Reader reader, Configuration cfg)
Constructs a template from a character stream.Template(java.lang.String name, java.lang.String sourceName, java.io.Reader reader, Configuration cfg, ParserConfiguration customParserConfiguration, java.lang.String encoding)
Same asTemplate(String, String, Reader, Configuration, String)
, but also specifies aTemplateConfiguration
.Template(java.lang.String name, java.lang.String sourceName, java.io.Reader reader, Configuration cfg, java.lang.String encoding)
Same asTemplate(String, String, Reader, Configuration)
, but also specifies the template's encoding (not recommended).
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
addImport(freemarker.core.LibraryLoad ll)
Deprecated.Should only be used internally, and might will be removed later.void
addMacro(freemarker.core.Macro macro)
Deprecated.Should only be used internally, and might will be removed later.void
addPrefixNSMapping(java.lang.String prefix, java.lang.String nsURI)
Deprecated.Should only be used internally, and might will be removed later.javax.swing.tree.TreePath
containingElements(int column, int line)
Deprecated.Should only be used internally, and might will be removed later.Environment
createProcessingEnvironment(java.lang.Object dataModel, java.io.Writer out)
Environment
createProcessingEnvironment(java.lang.Object dataModel, java.io.Writer out, ObjectWrapper wrapper)
Creates aEnvironment
object, using this template, the data-model provided as parameter.void
dump(java.io.PrintStream ps)
Dump the raw template in canonical form.void
dump(java.io.Writer out)
Dump the raw template in canonical form.int
getActualNamingConvention()
Returns the naming convention the parser has chosen for this template.int
getActualTagSyntax()
Returns the tag syntax the parser has chosen for this template.boolean
getAutoEscaping()
Returns if the template actually uses auto-escaping (seeConfiguration.setAutoEscapingPolicy(int)
).Configuration
getConfiguration()
Returns the Configuration object associated with this template.java.lang.Object
getCustomLookupCondition()
Gets the custom lookup condition with which this template was found.java.lang.String
getDefaultNS()
java.lang.String
getEncoding()
The encoding that was (allegedly) used to read this template; also the the default character encoding used for reading files included from this template.java.util.List
getImports()
Deprecated.Should only be used internally, and might will be removed later.int
getInterpolationSyntax()
Returns the interpolation syntax the parser has used for this template.java.util.Map
getMacros()
Deprecated.Should only be used internally, and might will be removed later.java.lang.String
getName()
The usually path-like (or URL-like) identifier of the template, or possiblynull
for non-stored templates.java.lang.String
getNamespaceForPrefix(java.lang.String prefix)
OutputFormat
getOutputFormat()
Returns the output format (seeConfiguration.setOutputFormat(OutputFormat)
) used for this template.ParserConfiguration
getParserConfiguration()
Returns theParserConfiguration
that was used for parsing this template.static Template
getPlainTextTemplate(java.lang.String name, java.lang.String content, Configuration config)
static Template
getPlainTextTemplate(java.lang.String name, java.lang.String sourceName, java.lang.String content, Configuration config)
Creates (not "get"-s) aTemplate
that only contains a single block of static text, no dynamic content.java.lang.String
getPrefixedName(java.lang.String localName, java.lang.String nsURI)
java.lang.String
getPrefixForNamespace(java.lang.String nsURI)
freemarker.core.TemplateElement
getRootTreeNode()
Deprecated.Should only be used internally, and might will be removed later.java.lang.String
getSource(int beginColumn, int beginLine, int endColumn, int endLine)
Returns the template source at the location specified by the coordinates given, ornull
if unavailable.java.lang.String
getSourceName()
The name that was actually used to load this template from theTemplateLoader
(or from other custom storage mechanism).void
process(java.lang.Object dataModel, java.io.Writer out)
Executes template, using the data-model provided, writing the generated output to the suppliedWriter
.void
process(java.lang.Object dataModel, java.io.Writer out, ObjectWrapper wrapper)
Likeprocess(Object, Writer)
, but overrides theConfigurable.getObjectWrapper()
.void
process(java.lang.Object dataModel, java.io.Writer out, ObjectWrapper wrapper, TemplateNodeModel rootNode)
Likeprocess(Object, Writer)
, but also sets a (XML-)node to be recursively processed by the template.void
setCustomLookupCondition(java.lang.Object customLookupCondition)
Mostly only used internally; setter pair ofgetCustomLookupCondition()
.void
setEncoding(java.lang.String encoding)
Deprecated.Should only be used internally, and might will be removed later.java.lang.String
toString()
Returns a string representing the raw template text in canonical form.-
Methods inherited from class freemarker.core.Configurable
addAutoImport, addAutoInclude, clone, doAutoImportsAndIncludes, getArithmeticEngine, getAttemptExceptionReporter, 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, getTruncateBuiltinAlgorithm, getURLEscapingCharset, getWrapUncheckedExceptions, hasCustomFormats, invalidSettingValueException, isAPIBuiltinEnabled, isAPIBuiltinEnabledSet, isArithmeticEngineSet, isAttemptExceptionReporterSet, isAutoFlushSet, isAutoImportsSet, isAutoIncludesSet, isBooleanFormatSet, isClassicCompatible, isClassicCompatibleSet, isCustomDateFormatsSet, isCustomNumberFormatsSet, isDateFormatSet, isDateTimeFormatSet, isLazyAutoImportsSet, isLazyImportsSet, isLocaleSet, isLogTemplateExceptionsSet, isNewBuiltinClassResolverSet, isNumberFormatSet, isObjectWrapperSet, isOutputEncodingSet, isShowErrorTipsSet, isSQLDateAndTimeTimeZoneSet, isTemplateExceptionHandlerSet, isTimeFormatSet, isTimeZoneSet, isTruncateBuiltinAlgorithmSet, isURLEscapingCharsetSet, isWrapUncheckedExceptionsSet, parseAsImportList, parseAsList, parseAsSegmentedList, removeAutoImport, removeAutoInclude, removeCustomAttribute, setAPIBuiltinEnabled, setArithmeticEngine, setAttemptExceptionReporter, setAutoFlush, setAutoImports, setAutoIncludes, setBooleanFormat, setClassicCompatible, setClassicCompatibleAsInt, setCustomAttribute, setCustomDateFormats, setCustomNumberFormats, setDateFormat, setDateTimeFormat, setLazyAutoImports, setLazyImports, setLocale, setLogTemplateExceptions, setNewBuiltinClassResolver, setNumberFormat, setObjectWrapper, setOutputEncoding, setSetting, setSettings, setSettings, setShowErrorTips, setSQLDateAndTimeTimeZone, setStrictBeanModels, setTemplateExceptionHandler, setTimeFormat, setTimeZone, settingValueAssignmentException, setTruncateBuiltinAlgorithm, setURLEscapingCharset, setWrapUncheckedExceptions, unknownSettingException
-
-
-
-
Field Detail
-
DEFAULT_NAMESPACE_PREFIX
public static final java.lang.String DEFAULT_NAMESPACE_PREFIX
- See Also:
- Constant Field Values
-
NO_NS_PREFIX
public static final java.lang.String NO_NS_PREFIX
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
Template
public Template(java.lang.String name, java.io.Reader reader, Configuration cfg) throws java.io.IOException
- Throws:
java.io.IOException
-
Template
public Template(java.lang.String name, java.lang.String sourceCode, Configuration cfg) throws java.io.IOException
Convenience constructor forTemplate(name, new StringReader(reader), cfg)
.- Throws:
java.io.IOException
- Since:
- 2.3.20
-
Template
public Template(java.lang.String name, java.io.Reader reader, Configuration cfg, java.lang.String encoding) throws java.io.IOException
Convenience constructor forTemplate(name, null, reader, cfg, encoding)
.- Throws:
java.io.IOException
-
Template
public Template(java.lang.String name, java.lang.String sourceName, java.io.Reader reader, Configuration cfg) throws java.io.IOException
Constructs a template from a character stream. Note that this is a relatively expensive operation; where higher performance matters, you should re-use (cache)Template
instances instead of re-creating them from the same source again and again. (and its overloads already do such reuse.
)- Parameters:
name
- The path of the template file relatively to the (virtual) directory that you use to store the templates (except ifsourceName
differs from it). Shouldn't start with'/'
. Should use'/'
, not'\'
. CheckgetName()
to see how the name will be used. The name should be independent of the actual storage mechanism and physical location as far as possible. Even when the templates are stored straightforwardly in real files (they often aren't; seeTemplateLoader
), the name shouldn't be an absolute file path. Like if the template is stored in"/www/templates/forum/main.ftl"
, and you are using"/www/templates/"
as the template root directory viaConfiguration.setDirectoryForTemplateLoading(java.io.File)
, then the template name will be"forum/main.ftl"
. The name can benull
(should be used for template made on-the-fly instead of being loaded from somewhere), in which case relative paths in it will be relative to the template root directory (and here again, it's theTemplateLoader
that knows what that "physically" means).sourceName
- SeegetSourceName()
for the meaning. Can benull
, in which casegetSourceName()
will return the same asgetName()
.reader
- The character stream to read from. It will always be closed (Reader.close()
) by this method (this is for backward compatibility; later major versions may discontinue this behavior). TheReader
need not be buffered, because this method ensures that it will be read in few kilobyte chunks, not byte by byte.cfg
- The Configuration object that this Template is associated with. If this isnull
, the "default"Configuration
object is used, which is highly discouraged, because it can easily lead to erroneous, unpredictable behavior. (See morehere...
)- Throws:
java.io.IOException
- Since:
- 2.3.22
-
Template
public Template(java.lang.String name, java.lang.String sourceName, java.io.Reader reader, Configuration cfg, java.lang.String encoding) throws java.io.IOException
Same asTemplate(String, String, Reader, Configuration)
, but also specifies the template's encoding (not recommended).- Parameters:
encoding
- This is the encoding that we are supposed to be using. At the first glance it's unnecessary because we already have aReader
(so decoding with the charset has already happened), however, if this is non-null
and there's an#ftl
header withencoding
parameter, they must match, or else aTemplate.WrongEncodingException
is thrown. Thus, it should be set if to decode the template, we were using an encoding (a charset), otherwise it should benull
. It's also kept as meta-info (returned bygetEncoding()
). It also has an impact when#include
-ing or#import
-ing another template from this template, as its default encoding will be this. But this behavior of said directives is considered to be harmful, and will be probably phased out.- Throws:
java.io.IOException
- Since:
- 2.3.22
-
Template
public Template(java.lang.String name, java.lang.String sourceName, java.io.Reader reader, Configuration cfg, ParserConfiguration customParserConfiguration, java.lang.String encoding) throws java.io.IOException
Same asTemplate(String, String, Reader, Configuration, String)
, but also specifies aTemplateConfiguration
. This is mostly meant to be used by FreeMarker internally, but advanced users might still find this useful.- Parameters:
customParserConfiguration
- Overrides the parsing related configuration settings of theConfiguration
parameter; can benull
. This is useful as theConfiguration
is normally a singleton shared by all templates, and so it's not good for specifying template-specific settings. (WhileTemplate
itself has methods to specify settings just for that template, those don't influence the parsing, and you only have opportunity to call them after the parsing anyway.) This objects is often aTemplateConfiguration
whose parent is theConfiguration
parameter, and then it practically just overrides some of the parser settings, as the others are inherited from theConfiguration
. Note that if this is aTemplateConfiguration
, you will also want to callTemplateConfiguration.apply(Template)
on the resultingTemplate
so thatConfigurable
settings will be set too, because this constructor only uses it as aParserConfiguration
.encoding
- Same as inTemplate(String, String, Reader, Configuration, String)
. When it's non-null
, it overrides the value coming from theTemplateConfiguration.getEncoding()
method of thetemplateConfiguration
parameter.- Throws:
java.io.IOException
- Since:
- 2.3.24
-
Template
@Deprecated public Template(java.lang.String name, java.io.Reader reader) throws java.io.IOException
Deprecated.This constructor uses the "default"Configuration
instance, which can easily lead to erroneous, unpredictable behavior. See morehere...
.Equivalent toTemplate(name, reader, null)
.- Throws:
java.io.IOException
-
-
Method Detail
-
getPlainTextTemplate
public static Template getPlainTextTemplate(java.lang.String name, java.lang.String content, Configuration config)
-
getPlainTextTemplate
public static Template getPlainTextTemplate(java.lang.String name, java.lang.String sourceName, java.lang.String content, Configuration config)
Creates (not "get"-s) aTemplate
that only contains a single block of static text, no dynamic content.- Parameters:
name
- SeegetName()
for more details.sourceName
- SeegetSourceName()
for more details. Ifnull
, it will be the same as thename
.content
- the block of text that this template representsconfig
- the configuration to which this template belongs- Since:
- 2.3.22
-
process
public void process(java.lang.Object dataModel, java.io.Writer out) throws TemplateException, java.io.IOException
Executes template, using the data-model provided, writing the generated output to the suppliedWriter
.For finer control over the runtime environment setup, such as per-HTTP-request configuring of FreeMarker settings, you may need to use
createProcessingEnvironment(Object, Writer)
instead.- Parameters:
dataModel
- the holder of the variables visible from the template (name-value pairs); usually aMap<String, Object>
or a JavaBean (where the JavaBean properties will be the variables). Can be any object that theObjectWrapper
in use turns into aTemplateHashModel
. You can also use an object that already implementsTemplateHashModel
; in that case it won't be wrapped. If it'snull
, an empty data model is used.out
- TheWriter
where the output of the template will go. Note that unless you have usedConfigurable.setAutoFlush(boolean)
to disable this,Writer.flush()
will be called at the when the template processing was finished.Writer.close()
is not called. Can't benull
.- Throws:
TemplateException
- if an exception occurs during template processingjava.io.IOException
- if an I/O exception occurs during writing to the writer.
-
process
public void process(java.lang.Object dataModel, java.io.Writer out, ObjectWrapper wrapper, TemplateNodeModel rootNode) throws TemplateException, java.io.IOException
Likeprocess(Object, Writer)
, but also sets a (XML-)node to be recursively processed by the template. That node is accessed in the template with .node, #recurse, etc. See the Declarative XML Processing as a typical example of recursive node processing.- Parameters:
rootNode
- The root node for recursive processing ornull
.- Throws:
TemplateException
- if an exception occurs during template processingjava.io.IOException
- if an I/O exception occurs during writing to the writer.
-
process
public void process(java.lang.Object dataModel, java.io.Writer out, ObjectWrapper wrapper) throws TemplateException, java.io.IOException
Likeprocess(Object, Writer)
, but overrides theConfigurable.getObjectWrapper()
.- Parameters:
wrapper
- TheObjectWrapper
to be used instead of whatConfigurable.getObjectWrapper()
provides, ornull
if you don't want to override that.- Throws:
TemplateException
java.io.IOException
-
createProcessingEnvironment
public Environment createProcessingEnvironment(java.lang.Object dataModel, java.io.Writer out, ObjectWrapper wrapper) throws TemplateException, java.io.IOException
Creates aEnvironment
object, using this template, the data-model provided as parameter. You have to callEnvironment.process()
on the return value to set off the actual rendering.Use this method if you want to do some special initialization on the
Environment
before template processing, or if you want to read theEnvironment
after template processing. Otherwise usingprocess(Object, Writer)
is simpler.Example:
Environment env = myTemplate.createProcessingEnvironment(root, out, null); env.process();
The above is equivalent with this:
myTemplate.process(root, out);
But with createProcessingEnvironment, you can manipulate the environment before and after the processing:
Environment env = myTemplate.createProcessingEnvironment(root, out); env.setLocale(myUsersPreferredLocale); env.setTimeZone(myUsersPreferredTimezone); env.process(); // output is rendered here TemplateModel x = env.getVariable("x"); // read back a variable set by the template
- Parameters:
dataModel
- the holder of the variables visible from all templates; seeprocess(Object, Writer)
for more details.wrapper
- TheObjectWrapper
to use to wrap objects intoTemplateModel
instances. Normally you left itnull
, in which caseConfigurable.getObjectWrapper()
will be used.out
- TheWriter
where the output of the template will go; seeprocess(Object, Writer)
for more details.- Returns:
- the
Environment
object created for processing. CallEnvironment.process()
to process the template. - Throws:
TemplateException
- if an exception occurs while setting up the Environment object.java.io.IOException
- if an exception occurs doing any auto-imports
-
createProcessingEnvironment
public Environment createProcessingEnvironment(java.lang.Object dataModel, java.io.Writer out) throws TemplateException, java.io.IOException
- Throws:
TemplateException
java.io.IOException
-
toString
public java.lang.String toString()
Returns a string representing the raw template text in canonical form.- Overrides:
toString
in classjava.lang.Object
-
getName
public java.lang.String getName()
The usually path-like (or URL-like) identifier of the template, or possiblynull
for non-stored templates. It usually looks like a relative UN*X path; it should use/
, not\
, and shouldn't start with/
(but there are no hard guarantees). It's not a real path in a file-system, it's just a name that aTemplateLoader
used to load the backing resource (in simple cases; actually that name isgetSourceName()
, but see it there). Or, it can also be a name that was never used to load the template (directly created withTemplate(String, Reader, Configuration)
). Even if the templates are stored straightforwardly in files, this is relative to the base directory of theTemplateLoader
. So it really could be anything, except that it has importance in these situations:Relative paths to other templates in this template will be resolved relatively to the directory part of this. Like if the template name is
"foo/this.ftl"
, then<#include "other.ftl">
gets the template with name"foo/other.ftl"
.You should not use this name to indicate error locations, or to find the actual templates in general, because localized lookup, acquisition and other lookup strategies can transform names before they get to the
TemplateLoader
(the template storage) mechanism. UsegetSourceName()
for these purposes.Some frameworks use URL-like template names like
"someSchema://foo/bar.ftl"
. FreeMarker understands this notation, so an absolute path like"/baaz.ftl"
in that template will be resolved too"someSchema://baaz.ftl"
.
-
getSourceName
public java.lang.String getSourceName()
The name that was actually used to load this template from theTemplateLoader
(or from other custom storage mechanism). This is what should be shown in error messages as the error location. This is usually the same asgetName()
, except when localized lookup, template acquisition (*
step in the name), or otherTemplateLookupStrategy
transforms the requested name (getName()
) to a different finalTemplateLoader
-level name. For example, when you get a template with name"foo.ftl"
then because of localized lookup, it's possible that something like"foo_en.ftl"
will be loaded behind the scenes. While the template name will be still the same as the requested template name ("foo.ftl"
), errors should point to"foo_de.ftl"
. Note that relative paths are always resolved relatively to thename
, not to thesourceName
.- Since:
- 2.3.22
-
getConfiguration
public Configuration getConfiguration()
Returns the Configuration object associated with this template.
-
getParserConfiguration
public ParserConfiguration getParserConfiguration()
Returns theParserConfiguration
that was used for parsing this template. This is most often the same object asgetConfiguration()
, but sometimes it's aTemplateConfiguration
, or something else. It's nevernull
.- Since:
- 2.3.24
-
setEncoding
@Deprecated public void setEncoding(java.lang.String encoding)
Deprecated.Should only be used internally, and might will be removed later.- Parameters:
encoding
- The encoding that was used to read this template. When this template#include
-s or#import
-s another template, by default it will use this encoding for those. For backward compatibility, this can benull
, which will unset this setting.
-
getEncoding
public java.lang.String getEncoding()
The encoding that was (allegedly) used to read this template; also the the default character encoding used for reading files included from this template. Possiblynull
, in which case you are supposed to useConfiguration.getEncoding(Locale)
.
-
getCustomLookupCondition
public java.lang.Object getCustomLookupCondition()
Gets the custom lookup condition with which this template was found. See thecustomLookupCondition
parameter ofConfiguration.getTemplate(String, java.util.Locale, Object, String, boolean, boolean)
for more explanation.- Since:
- 2.3.22
-
setCustomLookupCondition
public void setCustomLookupCondition(java.lang.Object customLookupCondition)
Mostly only used internally; setter pair ofgetCustomLookupCondition()
. This meant to be called directly after instantiating the template with its constructor, after a successfull lookup that used this condition. So this should only be called from code that deals with creating newTemplate
objects, like fromTemplateCache
.- Since:
- 2.3.22
-
getActualTagSyntax
public int getActualTagSyntax()
Returns the tag syntax the parser has chosen for this template. If the syntax could be determined, it'sConfiguration.SQUARE_BRACKET_TAG_SYNTAX
orConfiguration.ANGLE_BRACKET_TAG_SYNTAX
. If the syntax couldn't be determined (like because there was no tags in the template, or it was a plain text template), this returns whatever the default is in the current configuration, so it's maybeConfiguration.AUTO_DETECT_TAG_SYNTAX
.- Since:
- 2.3.20
- See Also:
Configuration.setTagSyntax(int)
-
getInterpolationSyntax
public int getInterpolationSyntax()
Returns the interpolation syntax the parser has used for this template. Because the interpolation syntax is never auto-detected, it's not called "getActualInterpolationSyntax" (unlikegetActualTagSyntax()
).- Returns:
- A constant like
Configuration.LEGACY_INTERPOLATION_SYNTAX
,Configuration.DOLLAR_INTERPOLATION_SYNTAX
, orConfiguration.SQUARE_BRACKET_INTERPOLATION_SYNTAX
. - Since:
- 2.3.28
- See Also:
Configuration.setInterpolationSyntax(int)
-
getActualNamingConvention
public int getActualNamingConvention()
Returns the naming convention the parser has chosen for this template. If it could be determined, it'sConfiguration.LEGACY_NAMING_CONVENTION
orConfiguration.CAMEL_CASE_NAMING_CONVENTION
. If it couldn't be determined (like because there no identifier that's part of the template language was used where the naming convention matters), this returns whatever the default is in the current configuration, so it's maybeConfiguration.AUTO_DETECT_TAG_SYNTAX
.- Since:
- 2.3.23
- See Also:
Configuration.setNamingConvention(int)
-
getOutputFormat
public OutputFormat getOutputFormat()
Returns the output format (seeConfiguration.setOutputFormat(OutputFormat)
) used for this template. The output format of a template can come from various places, in order of increasing priority:Configuration.getOutputFormat()
,ParserConfiguration.getOutputFormat()
(which is usually provided byConfiguration.getTemplateConfigurations()
) and the#ftl
header'soutput_format
option in the template.- Since:
- 2.3.24
-
getAutoEscaping
public boolean getAutoEscaping()
Returns if the template actually uses auto-escaping (seeConfiguration.setAutoEscapingPolicy(int)
). This value is decided by the parser based on the actualOutputFormat
, and the auto-escaping enums, in order of increasing priority:Configuration.getAutoEscapingPolicy()
,ParserConfiguration.getAutoEscapingPolicy()
(which is usually provided byConfiguration.getTemplateConfigurations()
), and finally on the#ftl
header'sauto_esc
option in the template.- Since:
- 2.3.24
-
dump
public void dump(java.io.PrintStream ps)
Dump the raw template in canonical form.
-
dump
public void dump(java.io.Writer out) throws java.io.IOException
Dump the raw template in canonical form.- Throws:
java.io.IOException
-
addMacro
@Deprecated public void addMacro(freemarker.core.Macro macro)
Deprecated.Should only be used internally, and might will be removed later.Called by code internally to maintain a table of macros
-
addImport
@Deprecated public void addImport(freemarker.core.LibraryLoad ll)
Deprecated.Should only be used internally, and might will be removed later.Called by code internally to maintain a list of imports
-
getSource
public java.lang.String getSource(int beginColumn, int beginLine, int endColumn, int endLine)
Returns the template source at the location specified by the coordinates given, ornull
if unavailable. A strange legacy in the behavior of this method is that it replaces tab characters with spaces according the value ofgetParserConfiguration()
/ParserConfiguration.getTabSize()
(which usually comes fromConfiguration.getTabSize()
), because tab characters move the column number with more than 1 in error messages. However, if you set the tab size to 1, this method leaves the tab characters as is.- Parameters:
beginColumn
- the first column of the requested source, 1-basedbeginLine
- the first line of the requested source, 1-basedendColumn
- the last column of the requested source, 1-basedendLine
- the last line of the requested source, 1-based- See Also:
TemplateObject.getSource()
-
getRootTreeNode
@Deprecated public freemarker.core.TemplateElement getRootTreeNode()
Deprecated.Should only be used internally, and might will be removed later.
-
getMacros
@Deprecated public java.util.Map getMacros()
Deprecated.Should only be used internally, and might will be removed later.
-
getImports
@Deprecated public java.util.List getImports()
Deprecated.Should only be used internally, and might will be removed later.
-
addPrefixNSMapping
@Deprecated public void addPrefixNSMapping(java.lang.String prefix, java.lang.String nsURI)
Deprecated.Should only be used internally, and might will be removed later.This is used internally.
-
getDefaultNS
public java.lang.String getDefaultNS()
-
getNamespaceForPrefix
public java.lang.String getNamespaceForPrefix(java.lang.String prefix)
- Returns:
- the NamespaceUri mapped to this prefix in this template. (Or null if there is none.)
-
getPrefixForNamespace
public java.lang.String getPrefixForNamespace(java.lang.String nsURI)
- Returns:
- the prefix mapped to this nsURI in this template. (Or null if there is none.)
-
getPrefixedName
public java.lang.String getPrefixedName(java.lang.String localName, java.lang.String nsURI)
- Returns:
- the prefixed name, based on the ns_prefixes defined in this template's header for the local name and node namespace passed in as parameters.
-
containingElements
@Deprecated public javax.swing.tree.TreePath containingElements(int column, int line)
Deprecated.Should only be used internally, and might will be removed later.- Returns:
- an array of the
TemplateElement
s containing the given column and line numbers.
-
-