- Configuring Velocity
- Configuration Summary Tree
- VTL Directives
- Resource Management
- Strict Reference Setting
- String Interpolation
- Parser Configuration
- Event Handlers
- String Interning
- Space Gobbling
- Configuration Examples
Velocity's runtime configuration is controlled by a set of configuration keys listed below. Generally, these keys will have values that consist of either a String, or a comma-separated list of Strings, referred to as a CSV for comma-separated values.
There is a set of default values contained in Velocity's jar, found in org/apache/velocity/runtime/defaults/velocity.properties, that Velocity uses as its configuration baseline. This ensures that Velocity will always have a 'correct' value for its configuration keys at startup, although it may not be what you want.
Any values specified before init() time will replace the default values. Therefore, you only have to configure velocity with the values for the keys that you need to change, and not worry about the rest. Further, as we add more features and configuration capability, you don't have to change your configuration files to suit - the Velocity engine will always have default values.
Please see the section Using Velocity for discussion on the configuration API.
The properties key names have been reviewed in Engine 2.1. Old names are still functional but will emit a deprecation warning in the log. See the table of correspondance.
Configuration Summary Tree¶
The following tree gathers all non deprecated configuration properties with their default values.
context. +-- scope_control. +-- define = false | +-- evaluate = false | +-- foreach = true | +-- macro = false | +-- template = false | +-- *somebodymacro* = false +-- self_reference_key = *key_name* directive. +-- define.max_depth = 2 +-- foreach. +-- max_loops = -1 | +-- skip_invalid = true +-- if.empty_check = true +-- parse.max_depth = 10 event_handler. +-- include.class = *classname*, *classname* ... +-- invalid_reference.class = *classname*, *classname* ... +-- method_exception.class = *classname*, *classname* ... +-- reference_insertion.class = *classname*, *classname* ... introspector. +-- conversion_handler. +-- class = org.apache.velocity.util.introspection.TypeConversionHandlerImpl | +-- instance = *Java Object instance* +-- uberspect.class = org.apache.velocity.util.introspection.UberspectImpl parser. +-- allow_hyphen_in_identifiers = false +-- pool. +-- class = org.apache.velocity.runtime.ParserPoolImpl | +-- size = 20 +-- space_gobbling = lines resource. +-- default_encoding = UTF-8 +-- loaders = file, ... +-- loader.*loader_name*. +-- class = *classname* | +-- instance = *Java Object instance* | +-- cache = false | +-- modification_check_interval = 2 | +-- *loader_prop* = ... +-- manager. +-- cache. +-- class = org.apache.velocity.runtime.resource.ResourceCacheImpl | +-- default_size = 89 +-- class = org.apache.velocity.runtime.resource.ResourceManagerImpl +-- instance = null +-- log_when_found = true runtime. +-- custom_directives = *classname*, *classname* ... +-- interpolate_string_literals = true +-- log. +-- instance = *Java Object instance* | +-- log_invalid_method_calls = true | +-- log_invalid_references = true | +-- name = org.apache.velocity +-- strict_math = false +-- strict_mode. +-- enable = false | +-- escape = false +--string_interning = true velocimacro. +-- arguments. +-- preserve_literals = false | +-- strict = false +-- body_reference = false +-- inline. +-- allow = true | +-- local_scope = false | +-- replace_global = false +-- library. +-- autoreload = false +-- path = velocimacros.vtl
runtime.log.instance = Java Object instance
Living Java instance, that must implement the interface org.slf4j.Logger. This property can only be set programmatically. By default, Velocity uses the SLF4J static discovery mechanism, see the Logging section in the dev guide.
runtime.log.name = org.apache.velocity
If no living Logger instance has been given using the previous property, Velocity will get a Logger object using the provided name.
runtime.log.log_invalid_references = true
Property to turn off the log output when a reference isn't valid. Good thing to turn off in production, but very valuable for debugging.
runtime.log.log_invalid_method_calls = true
Property to turn off the log output when a method call isn't valid or has thrown. Good thing to turn off in production, but very valuable for debugging.
directive.define.max_depth = 2
Defines the allowable parse depth for the #define directive.
directive.foreach.max_loops = -1
Maximum allowed number of loops for a #foreach() statement.
directive.foreach.skip_invalid = true
Tells #foreach to simply skip rendering when the object it is iterating over is not or cannot produce a valid Iterator.
directive.if.empty_check = true
When evaluating if a reference resolves to
falsein a boolean context, the engine first checks if its value is
null, if it is a
Booleanor if it has a public
getAsBoolean()method. Then, if none of this applies, the behavior depends upon this configuration flag:
false, no further check is performed and the object resolves to
true, the object is check for emptiness and zero value:
- return whether an array is empty.
- return whether a public
isEmpty()method exists and evaluates to false (
- return whether a public
length()method exists and evaluates to zero (
- return whether a public
size()method exists and evaluates to zero.
- return whether a
Numberstrictly equals zero.
- return whether a public
getAsString()method exists and evaluates to null or an empty string.
- return whether a public
getAsNumber()method exists and evaluates to null or strictly zero.
#include() and #parse() Directives¶
directive.include.output_error_start = <!-- include error :
directive.include.output_error_end = see error log -->
Deprecated. If/how errors are displayed is not the concern of the engine, which should throw in all cases. Defines the beginning and ending tags for an in-stream error message in the case of a problem with the #include() directive. If both the .start and .end tags are defined, an error message will be output to the stream, of the form '.start msg .end' where .start and .end refer to the property values. Output to the render stream will only occur if both the .start and .end (next) tag are defined.
directive.parse.max_depth = 10
Defines the allowable parse depth for a template. A template may #parse() another template which itself may have a #parse() directive. This value prevents runaway #parse() recursion.
runtime.custom_directives = empty
coma separated list of custom directives class names, which must inherit from
resource.default_encoding = UTF-8
Default character encoding for input (templates). UTF-8 if not specified.
resource.manager.instance = null
Living Java instance, that must implement the interface org.apache.velocity.runtime.resource.ResourceManager. This property can only be set programmatically, and takes precedence over the next property. It is otherwise used by Velocity to store its actual resource manager once instanciated.
resource.manager.class = org.apache.velocity.runtime.resource.ResourceManagerImpl
Replace the Velocity default Resource Manager class. A resource manager implementation must implement the (
org.apache.velocity.runtime.resource.ResourceManager)[apidocs/org/apache/velocity/runtime/resource/ResourceManager.html] interface. A description of the requirements of a resource manager is out of scope for this document. Implementors are encouraged to review the default implementation.
The following resource management configuration keys only apply to the default Resource Manager.
resource.manager.log_when_found = true
Switch to control logging of 'found' messages from resource manager. When a resource is found for the first time, the resource name and classname of the loader that found it will be noted in the runtime log.
resource.manager.cache.class = org.apache.velocity.runtime.resource.ResourceCacheImpl
Replace the Velocity default Resource Cache class. A resource cache implementation must implement the (
org.apache.velocity.runtime.resource.ResourceCache)[apidocs/org/apache/velocity/runtime/resource/ResourceCache.html] interface As with the resource manager. A description of the requirements of a resource manager is out of scope for this document. Implementors are encouraged to review the default implementation.
resource.manager.cache.default_size = 89
Sets the size of the default implementation of the resource manager cache size (in number of elements). When
resource.manager.cache.default_sizeis set to 0, then the default implementation uses the standard Java
ConcurrentHashMap. Otherwise, a non-zero cache size uses an LRU Map. The default cache size is 89. Note that the ConcurrentHashMap may be better at thread concurrency.
resource.loaders = file
Multi-valued key. Will accept CSV for value. Public name of a resource loader to be used. This public name will then be used in the specification of the specific properties for that resource loader. Note that as a multi-valued key, it's possible to pass a value like "file, string" (sans quotes), indicating that following will be configuration values for two loaders.
In a VelocityToolsView environment, VelocityView will override the default value and set it to
webapp, its webapp resource loader.
.description = Velocity File Resource Loader
Optional description string for the given loader.
.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
.path = .
Multi-valued key. Will accept CSV for value. Root(s) from which the loader loads templates. Templates may live in subdirectories of this root. ex. homesite/index.vm This configuration key applies currently to the FileResourceLoader and JarResourceLoader.
.cache = false
Controls caching of the templates in the loader. Default is false, to make life easy for development and debugging. This should be set to true for production deployment. When 'true', the
modificationCheckIntervalproperty applies. This allows for the efficiency of caching, with the convenience of controlled reloads - useful in a hosted or ISP environment where templates can be modifed frequently and bouncing the application or servlet engine is not desired or permitted.
.modificationCheckInterval = 2
This is the number of seconds between modification checks when caching is turned on. When this is an integer > 0, this represents the number of seconds between checks to see if the template was modified. If the template has been modified since last check, then it is reloaded and reparsed. Otherwise nothing is done. When <= 0, no modification checks will take place, and assuming that the property
cache(above) is true, once a template is loaded and parsed the first time it is used, it will not be checked or reloaded after that until the application or servlet engine is restarted.
To illustrate, here is an example taken right from the default Velocity properties, showing how setting up the FileResourceLoader is managed
resource.loaders = file resource.loader.file.description = Velocity File Resource Loader resource.loader.file.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader resource.loader.file.path = . resource.loader.file.cache = false resource.loader.file.modification_check_interval = 2
velocimacro.library.path = velocimacros.vtl
Multi-valued key. Will accept CSV for value. Filename(s) of Velocimacro library to be loaded when the Velocity Runtime engine starts. These Velocimacros are accessable to all templates. The file is assumed to be relative to the root of the file loader resource path. If the default (
velocimacro.vtlsince 2.1) is not found, the old default (
VM_global_library.vm) is also searched for.
velocimacro.inline.allow = true
Determines of the definition of new Velocimacros via the #macro() directive in templates is allowed. The default value is true, meaning any template can define and use new Velocimacros. Note that depending on other properties, those #macro() statements can replace global definitions.
velocimacro.inline.replace_global = false
Controls if a Velocimacro defind 'inline' in a template can replace a Velocimacro defined in a library loaded at startup.
velocimacro.inline.local_scope = false
Controls 'private' templates namespaces for Velocimacros. When true, a #macro() directive in a template creates a Velocimacro that is accessable only from the defining template. This means that Velocimacros cannot be shared unless they are in the global or local library loaded at startup. (See above.) It also means that templates cannot interfere with each other. This property also allows a technique where there is a 'default' Velocimacro definition in the global or local library, and a template can 'override' the implementation for use within that template. This occurrs because when this property is true, the template's namespace is searched for a Velocimacro before the global namespace, therefore allowing the override mechanism.
velocimacro.library.autoreload = false
Controls Velocimacro library autoloading. When set to
truethe source Velocimacro library for an invoked Velocimacro will be checked for changes, and reloaded if necessary. This allows you to change and test Velocimacro libraries without having to restart your application or servlet container, just like you can with regular templates. This mode only works when caching is off in the resource loaders (e.g.
resource.loader.file.cache = false). This feature is intended for development, not for production.
velocimacro.arguments.strict = false
When set to true, will throw a
ParseErrorExceptionwhen parsing a template containing a macro with an invalid number of arguments. Is set to false by default to maintain backwards compatibility with templates written before this feature became available.
velocimacro.arguments.preserve_literals = false
Since 2.0, inside a macro, the rendering of null arguments uses the local reference literal. For instance, the following VTL code#macro( display $foo ) $foo #end #display( $null )
$foo. To revert to the 1.x behavior, since 2.1, you can set this property to true. The previous code will then display
velocimacro.body_reference = false
Defines name of the reference that can be used to get the body content (an AST block) given for a block macro call (e.g. #@myMacro() has a body #end). The default reference name is "bodyContent" (e.g. $bodyContent). This block macro feature was introduced in Velocity 1.7.
Strict Reference Setting¶
runtime.strict_mode.enable = false
When set to true Velocity will throw a
MethodInvocationExceptionfor references that are not defined in the context, or have not been defined with a #set directive. This setting will also throw an exception if an attempt is made to call a non-existing property on an object or if the object is null. When this property is true then property
directive.foreach.skip_invaliddefaults to true, unless this later property is explicitly set to false. For a complete discussion see Strict References Setting.
runtime.strict_mode.escape = false
Changes escape behavior such that putting a forward slash before a reference or macro always escapes the reference or macro and absorbs the forward slash regardless if the reference or macro is defined. For example "\$foo" always renders as "$foo", or "#foo()" is always rendered as "#foo()". This escape behavior is of use in strict mode since unintended strings of characters that look like references or macros will throw an exception. This provides an easy way to escape these references. However, even in non-strict mode the developer may find this a more consistent and reliable method for escaping.
runtime.interpolate_string_literals = true
Controls interpolation mechanism of VTL String Literals. Note that a VTL StringLiteral is specifically a string using double quotes that is used in a #set() statement, a method call of a reference, a parameter to a VM, or as an argument to a VTL directive in general. See the VTL reference for further information.
runtime.strict_math = false
Affects all math operations in VTL. If changed to true, this will cause Velocity to throw a MathException whenever one side of a math operation has a null value (e.g.
#set( $foo = $null * 5 )) or when trying to divide by zero. If this value is left
false, then rendering will continue and that math operation will be ignored.
parser.pool.class = org.apache.velocity.runtime.ParserPoolImpl
This property selects the implementation for the parser pool. This class must implement ParserPool. Generally there is no reason to change this though if you are building a high volume web application you might consider including an alternate implementation that automatically adjusts the size of the pool.
parser.pool.size = 20
This property is used by the default pooling implementation to set the number of parser instances that Velocity will create at startup and keep in a pool. The default of 20 parsers should be more than enough for most uses. In the event that Velocity does run out of parsers, it will indicate so in the log, and dynamically create overflow instances as needed. Note that these extra parsers will not be added to the pool, and will be discarded after use. This will result in very slow operation compared to the normal usage of pooled parsers, but this is considered an exceptional condition. A web application using Velocity as its view engine might exhibit this behavior under extremely high concurrency (such as when getting Slashdotted). If you see a corresponding message referencing the
parser.pool.sizeproperty in your log files, please increment this property immediately to avoid performance degradation.
parser.allow_hyphen_in_identifiers = false
This is a backward compatibility option, false by default, which allows the '
-' character inside variable identifiers (available since 2.1). If enabled, be warned that you will have to surround the mathematical minus sign with spaces for it to be correctly interpreted.
See the Event Handlers section of the dev guide.
event_handler.include.class = classname, classname ...
register an include event handler.
event_handler.invalid_reference.class = classname, classname ...
register an invalid reference event handler.
event_handler.method_exception.class = classname, classname ...
register a method exception event handler.
event_handler.reference_insertion.class = classname, classname ...
register a reference insertion event handler.
Introspection is the process of mapping properties, methods and iterators of VTL references to Java objects. The object responsible of the introspection strategy in Velocity is called an uberspector.
introspector.uberspect.class = org.apache.velocity.util.introspection.UberspectImpl
This property sets the 'Uberspector', the introspection package that handles all introspection strategies for Velocity. You can specify a comma-separated list of Uberspector classes, in which case all Uberspectors are chained. The default chaining behaviour is to return the first non-null value for each introspection call among all provided uberspectors. You can modify this behaviour (for instance to restrict access to some methods) by subclassing org.apache.velocity.util.introspection.AbstractChainableUberspector (or implementing directly org.apache.velocity.util.introspection.ChainableUberspector). This allows you to create more interesting rules or patterns for Uberspection, rather than just returning the first non-null value.
Some alternate Uberspectors are provided within the Velocity package. Please refer to the Customizing Introspection section for a detailed list. You would for instance use
introspector.uberspect.class = org.apache.velocity.util.introspection.SecureUberspectorto avoid template authors to instanciate new classes or to use reflection, or use
introspector.uberspect.class = org.apache.velocity.util.introspection.UberspectImpl, org.apache.velocity.util.introspection.UberspectPublicFieldsto expose Java public fields in your templates.
introspector.conversion_handler.class = org.apache.velocity.util.introspection.TypeConversionHandlerImpl
This configuration option is only taken into account by the default uberspector (UberspectImpl) and its subclasses (like SecureUberspector). It can be set to:
none: the only accepted conversions for method arguments will be the ones accepted by Java, typically widening number conversions. This reflects the behavior of Velocity 1.x.
- classname: the name of a class implementing the interface org.apache.velocity.util.introspection.TypeConversionHandler or the deprecated (since 2.1) interface org.apache.velocity.util.introspection.ConversionHandler.
The default conversion handler will try to convert values between all number, boolean and string types (along with a Locale to string conversion since 2.1). Failed conversions will throw a MethodInvocationException (or call the registered MethodExceptionEventHandler, if any). Watch out for conversions towards boolean: non-zero numbers and the "true" String are true, everything else is false. This differs slighly from the
#if($reference)truthness rules, where all non-null numbers and all non-null and non-empty strings are true.
introspector.conversion_handler.instance = Java Object instance
This configuration option is only taken into account by the default uberspector (UberspectImpl) and its subclasses (like SecureUberspector). It can be set to a living Java instance of an object implementing the interface org.apache.velocity.util.introspection.TypeConversionHandler or the deprecated (since 2.1) interface org.apache.velocity.util.introspection.ConversionHandler.
context.self_reference_key = <key name>
This property has no default value. If present, the Context object will become accessible from the templates under the provided name. For instance, with the configuration "
context.self_reference_key = self", then
$selfwill contain the context itself. This feature is meant to be used for debugging purposes.
context.scope_control.define = false
Used to turn on the automatic provision of the $define scope control during #define() calls. The default is false. Set it to true if you want a local, managed namespace you can put references in when within a #define block or if you want it for more advanced #break usage.
context.scope_control.evaluate = false
Used to turn on the automatic provision of the $evaluate scope during #evaluate() or Velocity[Engine].evaluate(...) calls. The default is false. Set it to true if you want a local, managed namespace you can put references in during an evaluation or if you want it for more advanced #break usage.
context.scope_control.foreach = true
Used to control the automatic provision of the $foreach scope during #foreach calls. This gives access to the foreach status information (e.g. $foreach.index or $foreach.hasNext). The default is true. Set it to false if unused and you want a tiny performance boost.
context.scope_control.macro = false
Used to turn on the automatic provision of the $macro scope control during #macro calls. The default is false. Set it to true if you need a local namespace in macros or more advanced #break controls.
context.scope_control.template = false
Used to turn on the automatic provision of the $template scope control during #parse calls and template.merge(...) calls. The default is false. Set it to true if you want a secure namespace for your template variables or more advanced #break control.
context.scope_control.<somebodymacro> = false
Used to turn on the automatic provision of the $
scope control during a call to a macro with a body (e.g. #@foo #set($foo.a=$b) ... $foo.a #end). The default is false. Set it to true if you happen to need a namespace just for your macro's body content or more advanced #break controls.
runtime.string_interning = true
This property specifies whether to use Java (String interning)[https://en.wikipedia.org/wiki/String_interning] on identifiers. This may save some memory when set to true, and run a little bit faster when set to false.
parser.space_gobbling = lines
Space gobbling policy. See the Space Gobbling section in the developer guide. Possible values are: -
none: no space gobbling at all. -
bc: Velocity 1.x backward compatible space gobbling. -
lines: gobbles spaces and newline surrounding VTL directives alone in their line. -
structured: like previous, plus fix inner text blocks indentation.
Configuring the resource loaders for Velocity is straightforward. The properties that control the are listed in the resource configuration section, for further reference.
The first step in configuring one or more resource loaders is do 'declare' them by name to Velocity. Use the property
resource.loader and list one or more loader names. You can use anything you want - these names are used to associate configuration properties with a given loader.
resource.loaders = file
That entry declares that we will have a resource loader known as 'file'. The next thing to do is to set the important properties. The most critical is to declare the class to use as the loader:
resource.loader.file.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
In this case, we are telling velocity that we are setting up
a resource loadercalled 'file', and are using the class
org.apache.velocity.runtime.resource.loader.FileResourceLoader to be the class to use. The next thing we do is set the properties important to this loader.
resource.loader.file.path = /opt/templates resource.loader.file.cache = true resource.loader.file.modification_check_interval = 2
Here, we set a few things. First, we set the path to find the templates to be
/opt/templates. Second, we turned caching on, so that after a template or static file is read in, it is cached in memory. And finally, we set the modification check interval to 2 seconds, allowing Velocity to check for new templates.
Those are the basics. What follows are a few examples of different configuraitons.
Do-nothing Default Configuration: As the name says, there is nothing you have to do or configure to get the default configuration. This configuration uses the FileResourceLoader with the current directory as the default resource path, and caching is off. As a properties set, this is expressed as:
resource.loaders = file resource.loader.file.description = Velocity File Resource Loader resource.loader.file.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader resource.loader.file.path = . resource.loader.file.cache = false resource.loader.file.modification_check_interval = 0
Multiple Template Path Configuration: This configuration uses the FileResourceLoader with several directories as 'nodes' on the template search path. We also want to use caching, and have the templates checked for changes in 10 second intervals. As a properties set, this is expressed as:
resource.loaders = file resource.loader.file.description = Velocity File Resource Loader resource.loader.file.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader resource.loader.file.path = /opt/directory1, /opt/directory2 resource.loader.file.cache = true resource.loader.file.modification_check_interval = 10
Multiple Loader Configuration : This configuration sets up three loaders at the same time, the FileResourceLoader, the ClasspathResourceLoader, and the JarResourceLoader. The loaders are set-up such that the FileResourceLoader is consulted first, then the ClasspathResourceLoader, and finally the JarResourceLoader. This would allow you to qickly drop a template into the file template area to replace on of the templates found in the classpath (usually via a jar) without having to rebuild the jar.
# # specify three resource loaders to use # resource.loaders = file, class, jar # # for the loader we call 'file', set the FileResourceLoader as the # class to use, turn off caching, and use 3 directories for templates # resource.loader.file.description = Velocity File Resource Loader resource.loader.file.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader resource.loader.file.path = templatedirectory1, anotherdirectory, foo/bar resource.loader.file.cache = false resource.loader.file.modification_check_interval = 0 # # for the loader we call 'class', use the ClasspathResourceLoader # resource.loader.class.description = Velocity Classpath Resource Loader resource.loader.class.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader # # and finally, for the loader we call 'jar', use the JarResourceLoader # and specify two jars to load from # resource.loader.jar.description = Velocity Jar Resource Loader resource.loader.jar.class = org.apache.velocity.runtime.resource.loader.JarResourceLoader resource.loader.jar.path = jar:file:/myjarplace/myjar.jar, jar:file:/myjarplace/myjar2.jar
Node that the three names 'file', 'class', and 'jar' are merely for your convenience and sanity. They can be anything you want - they are just used to associate a set of properties together. However, it is recommended that you use names that give some hint of the function.
Note that while all three require very little configuration information for proper operation, the ClasspathResourceLoader is the simplest.
The following configuration maximizes the backward compatibility with Velocity 1.7.
# No automatic conversion of methods arguments introspector.conversion_handler.class = none # Use backward compatible space gobbling engine.space_gobbling = bc # Have #if($foo) only returns false if $foo is false or null directive.if.empty_check = false # Allow '-' in identifiers parser.allow_hyphen_in_identifiers = true # When displaying null arguments literals, use provided arguments literals velocimacro.arguments.preserve_literals = true