Class Template
- java.lang.Object
-
- freemarker.core.Configurable
-
- freemarker.core.TemplateCore
-
- freemarker.template.Template
-
public class Template extends TemplateCore
A core FreeMarker API that represents a compiled template. Typically, you will use a
Configurationobject to instantiate a template.Configuration cfg = new Configuration(); ... Template myTemplate = cfg.getTemplate("myTemplate.html");However, you can also construct a template directly by passing in to the appropriate constructor a java.io.Reader instance that is set to read the raw template text. The compiled template is stored in an an efficient data structure for later use.
To render the template, i.e. to merge it with a data model, and thus produce "cooked" output, call the process method.
Any error messages from exceptions thrown during compilation will be included in the output stream and thrown back to the calling code. To change this behavior, you can install custom exception handlers using
Configurable.setTemplateExceptionHandler(TemplateExceptionHandler)on a Configuration object (for all templates belonging to a configuration) or on a Template object (for a single template).It's not legal to modify the values of FreeMarker settings: a) while the template is executing; b) if the template object is already accessible from multiple threads.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classTemplate.WrongEncodingException-
Nested classes/interfaces inherited from class freemarker.core.Configurable
Configurable.UnknownSettingException
-
-
Field Summary
Fields Modifier and Type Field Description static StringDEFAULT_NAMESPACE_PREFIXstatic StringNO_NS_PREFIXstatic CodeSourceNULL_CODE_SOURCEprotected char[]templateText-
Fields 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_KEY
-
-
Constructor Summary
Constructors Modifier Constructor Description protectedTemplate(String name, Configuration cfg, CodeSource codeSource)A prime constructor to which all other constructors should delegate directly or indirectly.Template(String name, Reader reader)Deprecated.This constructor uses the "default"Configurationinstance, which can easily lead to erroneous, unpredictable behaviuour.Template(String name, Reader reader, Configuration cfg)This is equivalent to Template(name, reader, cfg, null)Template(String name, Reader reader, Configuration cfg, String encoding)Template(String name, Reader reader, Configuration cfg, String encoding, CodeSource codeSource)Constructs a template from a character stream.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddImport(freemarker.core.ast.LibraryLoad ll)Called by code internally to maintain a list of importsvoidaddParsingProblem(freemarker.core.parser.ParsingProblem problem)voidaddPrefixNSMapping(String prefix, String nsURI)This is used internally.List<freemarker.core.ast.TemplateElement>containingElements(int column, int line)EnvironmentcreateProcessingEnvironment(Object rootMap, Writer out)Same ascreateProcessingEnvironment(rootMap, out, null).EnvironmentcreateProcessingEnvironment(Object rootMap, Writer out, ObjectWrapper wrapper)Creates aEnvironmentobject, using this template, the data model provided as the root map object, and the supplied object wrapper to convert map elements to template models.booleandeclaresVariable(String name)voiddeclareVariable(String name)intgetAbsoluteOffset(int line, int column)CodeSourcegetCodeSource()ConfigurationgetConfiguration()Returns the Configuration object associated with this template.Set<String>getDeclaredVariables()StringgetDefaultNS()StringgetEncoding()Returns the character encoding used for reading included files.freemarker.core.ast.TemplateHeaderElementgetHeaderElement()List<freemarker.core.ast.LibraryLoad>getImports()StringgetLine(int lineNumber)StringgetName()The path of the template file relative to the directory what you use to store the templates.StringgetNamespaceForPrefix(String prefix)List<freemarker.core.parser.ParsingProblem>getParsingProblems()static TemplategetPlainTextTemplate(String name, String content, Configuration config)Returns a trivial template, one that is just a single block of plain text, no dynamic content.StringgetPrefixedName(String localName, String nsURI)StringgetPrefixForNamespace(String nsURI)freemarker.core.ast.TemplateElementgetRootTreeNode()StringgetSource(int beginColumn, int beginLine, int endColumn, int endLine)intgetTabAdjustedColumn(int lineNumber, int column, int tabSize)booleanhasParsingProblems()booleanisImplicitlyDeclared(String varname)only used internally, it says whether the variable was implicitly declared, that means not in a #var statement but either via a legacy #assign or as the name of a macro or as the namespace name in an #import This is rather tricky and only necessary for backward compatibility with older style #include'sbooleanisOutputtingLine(int i, boolean inMacro)booleanlineSaysLeftTrim(int i)booleanlineSaysNoTrim(int i)booleanlineSaysRightTrim(int i)voidmarkAsOutputtingLine(int lineNumber, boolean inMacro)voidprocess(Object rootMap, Writer out)Processes the template, using data from the map, and outputs the resulting text to the supplied Writer The elements of the map are converted to template models using the default object wrapper returned by thegetObjectWrapper()method of the Configuration.voidprocess(Object rootMap, Writer out, ObjectWrapper wrapper)Processes the template, using data from the root map object, and outputs the resulting text to the supplied writer, using the supplied object wrapper to convert map elements to template models.voidprocess(Object rootMap, Writer out, ObjectWrapper wrapper, TemplateNodeModel rootNode)Processes the template, using data from the root map object, and outputs the resulting text to the supplied writer, using the supplied object wrapper to convert map elements to template models.protected voidreadInTemplateText(Reader reader)voidsetEncoding(String encoding)Sets the character encoding to use for included files.voidsetHeaderElement(freemarker.core.ast.TemplateHeaderElement headerElement)voidsetImplicitlyDeclaredVariables(Set<String> names)Used internally, this is a complication necessary for backward compatibility in includes.voidsetLineSaysLeftTrim(int i)voidsetLineSaysNoTrim(int i)voidsetLineSaysRightTrim(int i)voidsetLineSaysTrim(int i)voidsetParent(Configurable parent)Reparenting support.voidsetStrictVariableDeclaration(boolean strictVariableDeclaration)voidsetStripWhitespace(boolean stripWhitespace)booleanstrictVariableDeclaration()StringtoString()Returns a string representing the raw template text in canonical form.voidwriteTemplateText(Writer out)voidwriteTextAt(Writer out, int beginColumn, int beginLine, int endColumn, int endLine)-
Methods inherited from class freemarker.core.TemplateCore
addMacro, checkModifyTemplate, dump, dump, getMacros, getRootElement, setRootElement
-
Methods inherited from class freemarker.core.Configurable
clone, doAutoImportsAndIncludes, getArithmeticEngine, getBooleanFormat, getBooleanFormat, getCustomAttribute, getCustomAttributeNames, getDateFormat, getDateTimeFormat, getEnvironment, getLocale, getNumberFormat, getObjectWrapper, getOutputEncoding, getParent, getSetting, getSettings, getTemplateExceptionHandler, getTimeFormat, getTimeZone, getURLEscapingCharset, invalidSettingValueException, removeCustomAttribute, setArithmeticEngine, setBooleanFormat, setCustomAttribute, setDateFormat, setDateTimeFormat, setLocale, setNumberFormat, setNumbersForComputers, setObjectWrapper, setOutputEncoding, setSetting, setSettings, setSettings, setStrictBeanModels, setTemplateExceptionHandler, setTimeFormat, setTimeZone, setURLEscapingCharset, unknownSettingException
-
-
-
-
Field Detail
-
NULL_CODE_SOURCE
public static final CodeSource NULL_CODE_SOURCE
-
DEFAULT_NAMESPACE_PREFIX
public static final String DEFAULT_NAMESPACE_PREFIX
- See Also:
- Constant Field Values
-
NO_NS_PREFIX
public static final String NO_NS_PREFIX
- See Also:
- Constant Field Values
-
templateText
protected char[] templateText
-
-
Constructor Detail
-
Template
protected Template(String name, Configuration cfg, CodeSource codeSource)
A prime constructor to which all other constructors should delegate directly or indirectly.
-
Template
public Template(String name, Reader reader, Configuration cfg, String encoding, CodeSource codeSource) throws IOException
Constructs a template from a character stream.- Parameters:
name- the path of the template file relative to the directory what you use to store the templates. SeegetName()for more details.reader- the character stream to read from. It will always be closed (Reader.close()).cfg- the Configuration object that this Template is associated with. If this is null, the "default"Configurationobject is used, which is highly discouraged, because it can easily lead to erroneous, unpredictable behaviour. (See morehere...)encoding- This is the encoding that we are supposed to be using. If this is non-null (It's not actually necessary because we are using a Reader) then it is checked against the encoding specified in the FTL header -- assuming that is specified, and if they don't match a WrongEncodingException is thrown.codeSource- the code source used to determine the security privileges for the template based on the Java policy in effect when it is run within a secured environment. Can be null, which is treated as being equivalent to untrusted code.- Throws:
IOException
-
Template
public Template(String name, Reader reader, Configuration cfg, String encoding) throws IOException
- Throws:
IOException
-
Template
public Template(String name, Reader reader, Configuration cfg) throws IOException
This is equivalent to Template(name, reader, cfg, null)- Throws:
IOException
-
Template
public Template(String name, Reader reader) throws IOException
Deprecated.This constructor uses the "default"Configurationinstance, which can easily lead to erroneous, unpredictable behaviuour. See morehere....Constructs a template from a character stream. This is the same as the 3 parameter version when you pass null as the cfg parameter.- Throws:
IOException
-
-
Method Detail
-
getAbsoluteOffset
public int getAbsoluteOffset(int line, int column)
-
readInTemplateText
protected void readInTemplateText(Reader reader) throws IOException
- Throws:
IOException
-
getPlainTextTemplate
public static Template getPlainTextTemplate(String name, String content, Configuration config)
Returns a trivial template, one that is just a single block of plain text, no dynamic content. (Used by the cache module to create unparsed templates.)- Parameters:
name- the path of the template file relative to the directory what you use to store the templates. SeegetName()for more details.content- the block of text that this template representsconfig- the configuration to which this template belongs
-
setStripWhitespace
public void setStripWhitespace(boolean stripWhitespace)
-
process
public void process(Object rootMap, Writer out) throws TemplateException, IOException
Processes the template, using data from the map, and outputs the resulting text to the supplied Writer The elements of the map are converted to template models using the default object wrapper returned by thegetObjectWrapper()method of the Configuration.- Parameters:
rootMap- the root node of the data model. If null, an empty data model is used. Can be any object that the effective object wrapper can turn into a TemplateHashModel. Basically, simple and beans wrapper can turn java.util.Map objects into hashes and the Jython wrapper can turn both a PyDictionary as well as any object that implements __getitem__ into a template hash. Naturally, you can pass any object directly implementing TemplateHashModel as well.out- a Writer to output the text to.- Throws:
TemplateException- if an exception occurs during template processingIOException- if an I/O exception occurs during writing to the writer.
-
process
public void process(Object rootMap, Writer out, ObjectWrapper wrapper, TemplateNodeModel rootNode) throws TemplateException, IOException
Processes the template, using data from the root map object, and outputs the resulting text to the supplied writer, using the supplied object wrapper to convert map elements to template models.- Parameters:
rootMap- the root node of the data model. If null, an empty data model is used. Can be any object that the effective object wrapper can turn into a TemplateHashModel Basically, simple and beans wrapper can turn java.util.Map objects into hashes and the Jython wrapper can turn both a PyDictionary as well as any object that implements __getitem__ into a template hash. Naturally, you can pass any object directly implementing TemplateHashModel as well.wrapper- The object wrapper to use to wrap objects intoTemplateModelinstances. If null, the default wrapper retrieved byConfigurable.getObjectWrapper()is used.out- the writer to output the text to.rootNode- The root node for recursive processing, this may be null.- Throws:
TemplateException- if an exception occurs during template processingIOException- if an I/O exception occurs during writing to the writer.
-
process
public void process(Object rootMap, Writer out, ObjectWrapper wrapper) throws TemplateException, IOException
Processes the template, using data from the root map object, and outputs the resulting text to the supplied writer, using the supplied object wrapper to convert map elements to template models.- Parameters:
rootMap- the root node of the data model. If null, an empty data model is used. Can be any object that the effective object wrapper can turn into a TemplateHashModel Basically, simple and beans wrapper can turn java.util.Map objects into hashes and the Jython wrapper can turn both a PyDictionary as well as any object that implements __getitem__ into a template hash. Naturally, you can pass any object directly implementing TemplateHashModel as well.wrapper- The object wrapper to use to wrap objects intoTemplateModelinstances. If null, the default wrapper retrieved byConfigurable.getObjectWrapper()is used.out- the writer to output the text to.- Throws:
TemplateException- if an exception occurs during template processingIOException- if an I/O exception occurs during writing to the writer.
-
createProcessingEnvironment
public Environment createProcessingEnvironment(Object rootMap, Writer out, ObjectWrapper wrapper) throws TemplateException
Creates aEnvironmentobject, using this template, the data model provided as the root map object, and the supplied object wrapper to convert map elements to template models. You can then call Environment.process() on the returned environment 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 the environment after template processing.Example:
This:
Environment env = myTemplate.createProcessingEnvironment(root, out, null); env.process();
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.include("include/common.ftl", null, true); // before processing env.process(); TemplateModel x = env.getVariable("x"); // after processing- Parameters:
rootMap- the root node of the data model. If null, an empty data model is used. Can be any object that the effective object wrapper can turn into a TemplateHashModel Basically, simple and beans wrapper can turn java.util.Map objects into hashes and the Jython wrapper can turn both a PyDictionary as well as any object that implements __getitem__ into a template hash. Naturally, you can pass any object directly implementing TemplateHashModel as well.wrapper- The object wrapper to use to wrap objects intoTemplateModelinstances. If null, the default wrapper retrieved byConfigurable.getObjectWrapper()is used.out- the writer to output the text to.- Returns:
- the
Environmentobject created for processing - Throws:
TemplateException- if an exception occurs while setting up the Environment object.
-
createProcessingEnvironment
public Environment createProcessingEnvironment(Object rootMap, Writer out) throws TemplateException, IOException
Same ascreateProcessingEnvironment(rootMap, out, null).
-
toString
public String toString()
Returns a string representing the raw template text in canonical form.
-
getName
public String getName()
The path of the template file relative to the directory what you use to store the templates. For example, if the real path of template is "/www/templates/community/forum.fm", and you use ""/www/templates" as"directoryForTemplateLoading", then name should be "community/forum.fm". The name is used for example when you use <include ...> and you give a path that is relative to the current template, or in error messages when FreeMarker logs an error while it processes the template.
-
getConfiguration
public Configuration getConfiguration()
Returns the Configuration object associated with this template.
-
getParsingProblems
public List<freemarker.core.parser.ParsingProblem> getParsingProblems()
-
hasParsingProblems
public boolean hasParsingProblems()
-
addParsingProblem
public void addParsingProblem(freemarker.core.parser.ParsingProblem problem)
-
setEncoding
public void setEncoding(String encoding)
Sets the character encoding to use for included files. Usually you don't set this value manually, instead it is assigned to the template upon loading.
-
getEncoding
public String getEncoding()
Returns the character encoding used for reading included files.
-
addImport
public void addImport(freemarker.core.ast.LibraryLoad ll)
Called by code internally to maintain a list of imports
-
setHeaderElement
public void setHeaderElement(freemarker.core.ast.TemplateHeaderElement headerElement)
-
getHeaderElement
public freemarker.core.ast.TemplateHeaderElement getHeaderElement()
-
declaresVariable
public boolean declaresVariable(String name)
-
declareVariable
public void declareVariable(String name)
-
setImplicitlyDeclaredVariables
public void setImplicitlyDeclaredVariables(Set<String> names)
Used internally, this is a complication necessary for backward compatibility in includes.
-
isImplicitlyDeclared
public boolean isImplicitlyDeclared(String varname)
only used internally, it says whether the variable was implicitly declared, that means not in a #var statement but either via a legacy #assign or as the name of a macro or as the namespace name in an #import This is rather tricky and only necessary for backward compatibility with older style #include's
-
strictVariableDeclaration
public boolean strictVariableDeclaration()
-
setStrictVariableDeclaration
public void setStrictVariableDeclaration(boolean strictVariableDeclaration)
-
getSource
public String getSource(int beginColumn, int beginLine, int endColumn, int endLine)
-
getLine
public String getLine(int lineNumber)
-
getTabAdjustedColumn
public int getTabAdjustedColumn(int lineNumber, int column, int tabSize)
-
writeTextAt
public void writeTextAt(Writer out, int beginColumn, int beginLine, int endColumn, int endLine) throws IOException
- Throws:
IOException
-
writeTemplateText
public void writeTemplateText(Writer out) throws IOException
- Throws:
IOException
-
setLineSaysLeftTrim
public void setLineSaysLeftTrim(int i)
-
setLineSaysRightTrim
public void setLineSaysRightTrim(int i)
-
setLineSaysTrim
public void setLineSaysTrim(int i)
-
setLineSaysNoTrim
public void setLineSaysNoTrim(int i)
-
lineSaysLeftTrim
public boolean lineSaysLeftTrim(int i)
-
lineSaysRightTrim
public boolean lineSaysRightTrim(int i)
-
lineSaysNoTrim
public boolean lineSaysNoTrim(int i)
-
markAsOutputtingLine
public void markAsOutputtingLine(int lineNumber, boolean inMacro)
-
isOutputtingLine
public boolean isOutputtingLine(int i, boolean inMacro)
-
getRootTreeNode
public freemarker.core.ast.TemplateElement getRootTreeNode()
- Returns:
- the root TemplateElement object.
- Throws:
SecurityException- if the getConfiguration().isSecure() returns true, there is a security manager in the JVM, and the caller of this method does not posess the "modifyTemplate" FreeMarker permission (since the retrieved root tree node is mutable).
-
setParent
public void setParent(Configurable parent)
Description copied from class:ConfigurableReparenting support. This is used by Environment when it includes a template - the included template becomes the parent configurable during its evaluation.- Overrides:
setParentin classConfigurable- Throws:
SecurityException- if the getConfiguration().isSecureTemplates() returns true, there is a security manager in the JVM, and the caller of this method does not posess the "modifyTemplate" FreeMarker permission.
-
getImports
public List<freemarker.core.ast.LibraryLoad> getImports()
-
getCodeSource
public CodeSource getCodeSource()
-
addPrefixNSMapping
public void addPrefixNSMapping(String prefix, String nsURI)
This is used internally.
-
getDefaultNS
public String getDefaultNS()
-
getNamespaceForPrefix
public String getNamespaceForPrefix(String prefix)
- Returns:
- the NamespaceUri mapped to this prefix in this template. (Or null if there is none.)
-
getPrefixForNamespace
public String getPrefixForNamespace(String nsURI)
- Returns:
- the prefix mapped to this nsURI in this template. (Or null if there is none.)
-
getPrefixedName
public String getPrefixedName(String localName, 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
public List<freemarker.core.ast.TemplateElement> containingElements(int column, int line)
- Parameters:
column- the columnline- the line- Returns:
- an array of the elements containing the given column and line numbers.
- Throws:
SecurityException- if the getConfiguration().isSecureTemplates() returns true, there is a security manager in the JVM, and the caller of this method does not posess the "modifyTemplate" FreeMarker permission.
-
-