Search code examples
xmlfreemarker

NonStringException in FreeMarker template when output_format is set


I have a FreeMarker template where I want to specify the output format in order to escape some characters in my XML files. The template example looks as below:

<#ftl output_format="XML">
<#assign field1>
   TestField&1&
</#assign>
<#assign field2>
   <#if field1?trim?length == 0>
      TestField&1&
   <#else>
      TestField&2&
   </#if>
</#assign>
<?xml version="1.0" encoding="UTF-8"?>
<FIELD2>${field2}</FIELD2>

The transformation works fine (except the escaping), unless I put the <#ftl output_format="XML"> directive in my template. After that I get a NonStringException:

freemarker.core.NonStringException: For "?trim" left-hand operand: Expected a string or something automatically convertible to string (number, date or boolean), but this has evaluated to a markup_output (wrapper: f.c.TemplateXMLOutputModel): ==> field1 [in template "Test.ftl" at line 6, column 9]

Basically field1?trim?length does not work, because field1 is not evaluated as a string anymore.

Without the output format directive everything woks as expected.
FreeMarker version I'm using is 2.3.26-incubating.


Solution

  • You can use the markup_string builtin, which returns the markup stored inside a markup output value as string.

    <#ftl output_format="XML">
    <#assign field1>
        TestField&1&
    </#assign>
    <#assign field2>
        <#if field1?markup_string?trim?length == 0>
            TestField&1&
        <#else>
            TestField&2&
        </#if>
    </#assign>
    <?xml version="1.0" encoding="UTF-8"?>
    <FIELD2>${field2}</FIELD2>