TWIG: capitalize makes other letters small

You can create a new filter that return your string using the php function ucfirst.


You can just do this:

{{ variable[:1]|upper ~ variable[1:] }}

from https://github.com/twigphp/Twig/issues/1652


Just to illustrate a good twig practice solution, you can create a custom Utilities Twig Extension and consider Multibyte String (mb) for strings starting with accents, to work properly:

use Twig_SimpleFilter;

class UtilitiesExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new Twig_SimpleFilter('ucfirst', 
                array($this, 'ucFirst'), array('needs_environment' => true)
            ),
        );
    }

    public function ucFirst(Twig_Environment $env, $string)
    {
        if (null !== $charset = $env->getCharset()) {
            $prefix = mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset);
            $suffix = mb_substr($string, 1, mb_strlen($string, $charset));
            return sprintf('%s%s', $prefix, $suffix); 
        }
        return ucfirst(strtolower($string));
    }
}

Then you can call such filter from a twig file in the way. Accents even work:

{{ 'étudiant de PHP' | ucfirst }}

Results in: "Étudiant de PHP"