We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Conditional truncate and append?

Does Volt have a function or filter for doing a truncation, with an optional appended character? Where the appended character would only be appended if the original string was longer than the desired truncate length?

For example:

{{ truncate('This is a long string',7,'...') }}

renders as This is...

Whereas

{{ truncate('Short',7,'...') }}

renders as Short

I couldn't readily find something like this in the documentation.

Turns out it's relatively simple to do:

$Compiler->addFunction('truncate',function($resolvedArgs,$expArgs) use ($Compiler){
    $string = $Compiler->expression($expArgs[0]['expr']);
    $length = $Compiler->expression($expArgs[1]['expr']);
    $append = (isset($expArgs[2])) ? $Compiler->expression($expArgs[2]['expr']) : '';

    return "(strlen($string) < $length) ? substr($string,0,$length) : substr($string,0,$length).$append;";
});

I'm still interested if there's built-in functionality for this.

Your solution looks like a good solution to me