Search code examples
freemarker

Freemarker: how to disable whitespace stripping inside variables


I'm using Freemarker 2.3.30 in a Java application with DOCX templates. In some complex scenarios we need to do string length calculations and conditional string concatenation at character level precision (including whitespaces). I've run in the following issue. This is a simplified piece of template:

enter image description here

  1. I have a separator variable containing a comma and a whitespace (which needs to be accounted)
  2. I use the separator to concatenate two strings
  3. I just append the separator to one string

Below the output.

enter image description here

The output of [2] properly includes the whitespace after the comma; in the output of [3] the whitespace is trimmed. What I'm trying to achieve is to have the trailing whitespace to be always preserved even when there is no string appended.

I've found no Freemarker configuration option which could affect this behaviour.

If I define the separator sequence (, ) within a macro the whitespace is preserved, but then I'm not able to do string length calculations and manipulations anymore.

Any suggestion/hint is welcome. Kind Regards


Solution

  • FreeMarker doesn't trim that whitespace, as its whitespace trimming only removes whitespace that's present in the template itself (i.e., it's parse-time trimming, not runtime). I suspect the space is removed on a higher level. Like perhaps it's there in the generated XML, but then not rendered visually, which is how XML/SGML schemas commonly treat leading and trailing whitespace of visual blocks. Like HTML does that too.