How to name ucwords in a twig?

EDIT: Dec 3, 2016

I found several posts about calling php functions from the branch which show it should be supported, however it doesn't work.

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

results in: l

Subtle application error

The application cannot work due to the following error:

More details

Type: Message Twig_Error_Syntax: Function "ucwords" does not exist in "home.twig" on line 101

File: /usr/share/dev89/html/vhosts/local/libs/vendor/twig/twig/lib/Twig/ExpressionParser.php Line: 572

+4


source to share


4 answers


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

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 Twig_SimpleFunction

/ Twig_SimpleFilter

is the name of the / filter function in Twig. The second parameter is PHP to be called. Since the function ucfirst

already exists, it is sufficient to pass its name as a string.



Test in Twig:

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

      

Return:

Test Foobar
Test Foobar

      

+7


source


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

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

PHP function:



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

      

+22


source


You can use the capize twig parameter :

{{ item | capitalize }}

      

+3


source


Why not use a filter title

? I also searched for a filter for a function ucwords()

and found this filter in the Twig documentation .

Usage example;

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

      

Results: I am Raziul Islam

0


source







All Articles