Last Updated: March 18, 2016
·
2.08K
· raphaelstolt

Adding Twig_SimpleFilter to a Silex application

Sometimes the provided Twig filters are insufficient. For example you might want to camelize (uppercase the first character of each word in a string) a value instead of just to capitalize (uppercase the first character and lowercase each other word in a string) it. Luckily Pimple allows to add simple filters to the Twig_Environment class of a Silex\Application via an anonymous function.

<?php
// other silex app bootstrapping aspects omitted 
$app->register(new TwigServiceProvider(), array(
  'twig.path' => 'assets/views',
));

$app['twig'] = $app->share($app->extend('twig', function($twig) {
  $twig->addFilter(new Twig_SimpleFilter('camelize', function ($str) {
    return ucwords($str);
  }));
  return $twig;
}));

Inside a Twig view the filter is now aviable via the defined filter name, i.e. camelize.

<span id="used-filter">{{ used_filter|camelize }}</span>