Limit string length in FreeMarker

Bart Vangeneugden picture Bart Vangeneugden · Aug 3, 2010 · Viewed 21.6k times · Source

I'm trying to get a substring from a string in FreeMarker. However there are 2 thigns to consider:

  1. The string can be null
  2. The string can be shorter then the maximum string length

I do the following:

<#list landingpage1.popularItems as row>
    <li>
        <span class="minititle">
            <#assign minititle=(row.title!"")>
            <#if minititle?length &lt; 27>
                ${minititle}
            <#else>
                ${minititle?substring(0,26)} ...
            <#/if>
        </span>
    </li>
</#list>

I get a freemarker error saying:

Failed to load templates: Encountered "</#list>" at line 144, column 65 in landingpage1.ftl.
Was expecting one of:
    <ATTEMPT> ...
    <IF> ...
    <LIST> ...
    <FOREACH> ...
    <SWITCH> ...
    <ASSIGN> ...
    <GLOBALASSIGN> ...
    <LOCALASSIGN> ...
    <INCLUDE> ...
    <IMPORT> ...
    <FUNCTION> ...
    <MACRO> ...
    <TRANSFORM> ...
    <VISIT> ...
    <STOP> ...
    <RETURN> ...
    <CALL> ...
    <SETTING> ...
    <COMPRESS> ...
    <COMMENT> ...
    <TERSE_COMMENT> ...
    <NOPARSE> ...
    <END_IF> ...
    <BREAK> ...
    <SIMPLE_RETURN> ...
    <HALT> ...
    <FLUSH> ...
    <TRIM> ...
    <LTRIM> ...
    <RTRIM> ...
    <NOTRIM> ...
    <SIMPLE_NESTED> ...
    <NESTED> ...
    <SIMPLE_RECURSE> ...
    <RECURSE> ...
    <FALLBACK> ...
    <ESCAPE> ...
    <NOESCAPE> ...
    <UNIFIED_CALL> ...
    <WHITESPACE> ...
    <PRINTABLE_CHARS> ...
    <FALSE_ALERT> ...
    "${" ...
    "#{" ...

Very odd. Can anybody help?

Answer

Bart Vangeneugden picture Bart Vangeneugden · Aug 3, 2010

The error magically solved itself after extensive testing. Must be karma.

My final code for safe checking:

<#assign minititle=(row.title!"")>
<#if minititle?length &lt; 27>
${minititle}
<#else>
${minititle?substring(0,26)} ...
</#if>

Hope it helps somebody else