Extending Velocity

Last Updated: Nov 4, 2024
documentation for the dotCMS Content Management System

Macros can be placed directly inside of your plugin within the conf/macros-ext.vm file. If you declare a macro that already exists the previous macro will be commented out and your new version of the macro will be used.

Custom macros can be written here as in the following example:

#macro (newMacro $newMacroParameter)
Macro Code written here (or another file with macro code can be parsed or included)
#end

After creating the custom macro, and saving it to the recommended .vm file, it can then be called from any piece of content, container, or template as any other macro:

#newMacro($newMacroParameter)

Per best practices, remember to ensure all macros have unique names, to ensure the correct macros are executed at runtime.

Note:

While it is possible to add macros to any velocity page or file, it is important that you add all Velocity macros to files with a .vm extension, to ensure that your macros are cached properly. Inclusion of macros in pages or in files with extensions other than .vm (including .vtl files that contain other Velocity vode) may cause your pages to render incorrectly.

There are three methods to extend Velocity with your own code:

MethodDescriptionSyntaxScopePerformanceNotes
Directives?????GlobalGoodGood for code that requires awareness of the context in which it's used, such as transforming the output of the section it encloses in some way.
MacrosBlocks of Velocity code which can be called from within Velocity.VelocityLocal (only where explicitly included)PoorAllows you to re-use the same Velocity code or content in without repeating it and having to maintain it in multiple locations.
ViewtoolsJava classes that can be mapped to Velocity objects and methods.JavaGlobal (via the toolbox.xml fileExcellentAllows you to provide access to virtually any objects, methods, and libraries in Velocity.

The third way is called “tools”. The VelocityTools project has many of these you can use or use as examples, not to mention support code for really easy tool management. Anyway, tools are primarily for accessing or manipulating your data. Don't create a directive or a macro that does number formatting. Use a tool. Tools provide a VTL-friendly interface to libraries and APIs that are otherwise difficult to use within templates. They can be access-controlled and scoped in ways that directives and macros never can.

All three are very useful, for different things. In short:

directives are best for manipulating the AST or the output of template sections macros are best for not repeating yourself or letting markup sneak into java code tools are best for accessing and manipulating the data in the template

On this page

×

We Dig Feedback

Selected excerpt:

×