A simple Twig truncate filter - Silex

Written by Erika Heidi on Wednesday March 20, 2013 - Permalink - Category: PHP - Tags: silex, filter, truncate - Lang: eng

Sometimes you can get in trouble when dealing with dynamic data with variable length, such as titles and descriptions, so they can fit well in your layout. With Smarty you have the built-in filter "truncate", but Twig doesn't have this filter by default. I know there's some text extensions available, but I didn't get it to work with Silex easily and I didn't want to lose more time on this issue, so I made this simple twig truncate filter and it's working perfectly for truncating strings in the smarty style. Just add this to your bootstrap.php (or whatever initialization file you use), after registering the Twig Extension:

<?php
$app['twig']->addFilter(new Twig_SimpleFilter('truncate', function($string, $size) {
    if(strlen($string) < $size) {
        return $string;
    } else {
        return array_shift(str_split($string, $size)) . "...";
    }
));

Use it like this:

{{ my_big_title|truncate(10) }}

The code below will truncate your title to 10 characters, including a '...' at the end of the string.

comments powered by Disqus