How can I limit a string length? I\'m getting a description value from my database, but I want to only display a number of specific characters.
So there's a couple of options listed above that aren't given any detail, so here's a bit more info:
{{ variable.description|truncate(100) }}
This will cut your text off at 100 characters exactly. The problem here is that if the 100th character is in the middle of a word, that word will be cut in half.
So to work around this, we can add 'true' into the truncate call:
{{ variable.description|truncate(100, true) }}
When we do this, truncate will check to see if we are in the middle of a word at the cut-off point and if we are, it will cut the string at the end of that word.
If we're also looking to truncate a string that may contain some HTML, we need to strip those tags away first:
{{ (variable.description|striptags)|truncate(100) }}
The only slight disadvantage to this is that we will lose any newline characters (such as those built into paragraph tags). If you are truncating a relatively short string though, this will possibly not be an issue.