Search code examples
typo3fluidtypo3-9.x

Get length of string in TYPO3 Fluid template


How can I check the length of a string? I want to add a class if under 8 characters.

So something like:

{f:if(condition: '{page.title -> f:count()} < 8', then: ' large')}

Solution

  • With a little trick it is possible with Fluid:

    You crop the string to its maximum length and compare the result to the original string. If the cropped string does not match the original, the original string was longer than desired.

    {f:if(condition: '{page.title} != {page.title -> f:format.crop(maxCharacters: 8, append:\'\')}', then: ' large')}
    

    Attention: append must be set to an empty string.

    Example

    lib.stringLength = FLUIDTEMPLATE
    lib.stringLength {
        variables {
            shortText = TEXT
            shortText.value = abc
            exactText = TEXT
            exactText.value = four
            longText = TEXT
            longText.value = Lorem ipsum
        }
        template = TEXT
        template.value(
            <h2>{shortText}</h2>
            <p>condition: '{shortText} != {shortText -> f:format.crop(maxCharacters: 4, append:'')}': <br />
                result: {f:if(condition: '{shortText} != {shortText -> f:format.crop(maxCharacters: 4, append:\'\')}', then: ' large')}
            </p>
            <hr />
            <h2>{exactText}</h2>
            <p>condition: '{exactText} != {exactText -> f:format.crop(maxCharacters: 4, append:'')}': <br />
                result: {f:if(condition: '{exactText} != {exactText -> f:format.crop(maxCharacters: 4, append:\'\')}', then: ' large')}
            </p>
            <hr />
            <h2>{longText}</h2>
            <p>condition: '{longText} != {longText -> f:format.crop(maxCharacters: 4, append:'')}': <br />
                result: {f:if(condition: '{longText} != {longText -> f:format.crop(maxCharacters: 4, append:\'\')}', then: ' large')}
            </p>
            <hr />
        )
    }
    

    Result:

    abc

    condition: 'abc != abc':

    result:

    four

    condition: 'four != four':

    result:

    Lorem ipsum

    condition: 'Lorem ipsum != Lore':

    result: large