How to call ucwords in twig?

As @lxg said, it's not possible to call all PHP functions from Twig templates ... unless you want to do that and define your own filters/functions. Instead of a drawback, this is a good thing to "force" you to create good templates that don't contain too much logic.

Anyway, in this particular case, Twig already contains a filter called title which applies the "title case", which is equivalent to the ucwords() PHP function:

{{ item|replace({'_':' '})|title }}

Update: Twig 2.x comes with the capitalize filter which does exactly that.


It is not true that all PHP functions are available in Twig. Only a few Twig filters and functions go by the same names as their equivalents in PHP.

But you can easily create your own Twig extension for ucwords – filter as well as function:

<?php

namespace Acme\TestBundle\Twig;

class UcWordsExtension extends \Twig_Extension
{
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('ucwords', 'ucwords')
        ];
    }

    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('ucwords', 'ucwords')
        ];
    }
    
    public function getName()
    {
        return 'ext.ucwords';
    }

}

The first parameter of Twig_SimpleFunction/Twig_SimpleFilter is the name of the function/filter in Twig. The second parameter is a PHP callable. As the ucfirst function already exists, it is sufficient to pass its name as a string.

Test in Twig:

{{ "test foobar"|ucwords }} {# filter #} <br>
{{ ucwords("test foobar") }} {# function #} 

Returns:

Test Foobar
Test Foobar

Why not use title filter? I was looking for a filter that will work as like ucwords() php function and I found this title filter in Twig Documentation.

Usage example;

{{ 'i am raziul islam'|title }}

Outputs: I Am Raziul Islam

Tags:

Twig