3
votes

So I'm pretty new to Symfony2 and I'm trying to use the camelize filter in a twig template. However when I request the page I get an error saying that the filter doesn't exist:

The filter "camelize" does not exist in ::base.html.twig

Here's the line from my template file:

{{ 'hello world' | camelize }}

The filter is listed on Twig's quick reference page.

I'm confused, doesn't Symfony2 support all of twig's filters? There seem to be quite a few missing, why? And if it doesn't support them, then is there any way to add the missing ones in?

Thanks in advance!

edit Ok, so it turns out I'm retarded and I need to remember to check that I've actually got the right git project. No wonder I was confused. Thanks replies!

4
I don't know where you got that reference page, but that doesn't seem to be the correct Twig.Squazic

4 Answers

11
votes

Symfony 2 has title filter for camel case use

{{ entity.yourstring | title }}

to camel case your string

9
votes

Your link points to a fork on GitHub, meaning a modified copy of the original project. The original project is https://github.com/fabpot/Twig.

There is no camelize filter in Twig. Built-in filters are here. You can write your own camilize filter (it's easy, actually...) following this tutorial: How to write a custom Twig Extension.

EDIT: just for fun, you can write something like:

class MyTwigExtension extends Twig_Extension
{
    public function getFilters()
    {
        return array(
            'camelize' => new Twig_Filter_Method($this, 'camelizeFilter'),
        );
    }

    public function camelizeFilter($value)
    {
        if(!is_string($value)) {
            return $value;
        }

        $chunks    = explode(' ', $value);
        $ucfirsted = array_map(function($s) { return ucfirst($s); }, $chunks);

        return implode('', $ucfirsted);
    }

    public function getName()
    {
        return 'my_twig_extension';
    }
}

Note that this is a quick and dirty filter! Take a look at the built-in filters to learn best practice!

0
votes

Here is the best solution by default in Craft CMS 3

Craft 3 now has a |camel filter for twig

https://docs.craftcms.com/v3/dev/filters.html#camel

{{ 'foo bar'|camel }}
{# Output: fooBar #}