Velocity Macro Filter

Last modified by Thomas Mortagne on 2023/10/10 14:28

XWiki Platform 1.9 introduced the possibility to filter the Velocity macro content before and after the Velocity Engine execution.

You can set the default filter to use in xwiki.properties by the setting the property macro.velocity.filter. You can also set the filter to use directly when writing the macro by setting the macro filter parameter as you can see in the previous table.

Existing filters

By default the provided filters are:

none

macro.velocity.filter=none
macro.velocity.filter=
{{macro filter="none"}}
{{macro filter=""}}

Do nothing, it's what happened before XWiki Platform 1.9

indent

macro.velocity.filter=indent
{{macro filter="indent"}}

Remove all first whites spaces of lines to support source code indentation without generating whitespace in the resulting HTML.

#if (test)
 Some Text
#end

Is the same as

#if (test)
Some Text
#end

html

macro.velocity.filter=html
{{macro filter="html"}}

The goal is to make the velocity script more readable by supporting indentation and code organization with empty lines and putting if/else/.. on their own lines.

This is done by applying a html like cleaning on white spaces and new lines meaning that any group of spaces/new lines is replaced by a space except for some specific use cases which are:

  • spaces and new lines following a velocity keyword like if/else/... are removed instead of replaced by a space
  • spaces before a velocity keyword like if/else/... are removed
  • white spaces and new lines before and after $nl are removed instead of replaced by a space

So for example:

{{velocity}}
The beginning of the line

#if (true)
  #if (true)
   followed by the end of the line.
  #else
    .
  #end
#else
  .
#end
{{/velocity}}

will generate

<p>The beginning of the line followed by the end of the line. <p>

instead of

<p>The beginning of the line
<br/>
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;followed by the end of the line.
<br/>
<p>

The filter inject the mapping $sp and $nl to be able to force a space of a new line (like putting a <br/> in html).

Create a custom filter

The velocity macro content filter are xwiki components so to add one you just need to implements VelocityMacroFilter component interface and set the right component attributes. See WritingComponents for more details on XWiki components.

Get Connected