Call Twig truncate filter inside a controller

Probably there is a shorter way, but the following worked for me:

$filters = $this->get('twig.extension.text')->getFilters();
$callable = $filters['truncate']->getCallable();

$truncated = $callable($this->get('twig'), $str));

For Twig Extensions > 1.3 you can use this

$filters = $this->get('twig.extension.text')->getFilters();
$key = array_search('truncate', array_map(function(TwigFilter $filter) { return $filter->getName(); }, $filters), true);
$callable = $filters[$key]->getCallable();
    
$truncated = $callable($this->get('twig'), $str));

If you look closely at the Twig/Extensions/Extension/Text file, you'll see that twig_truncate_filter is actually declared as a global function, not part of the Twig_Extensions_Extension_Text class.

That class merely acts as a wrapper for a Twig filter, truncate, to call that global twig_truncate_filter function.

You can simply call it directly in your controller:

$truncatedValue = twig_truncate_filter($twig, $something);

Tags:

Php

Twig

Symfony