Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig add space at camel case letter

Tags:

twig

symfony

Is there a way in Twig to add a space where the word has camel case letters.

For instance: helloWorldHowAreYouDoing would be hello World How Are You Doing

Thanks!

like image 766
LargeTuna Avatar asked Sep 01 '25 16:09

LargeTuna


1 Answers

From php version 5.5 the preg_replace_callback function is required as the "/e" modifier is now deprecated.

Create an extension method and call it from the twig page as a filter.

Extension Class:

<?php

// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;

class yourExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('camelToSpace', array($this, 'convertCamelCaseToHaveSpacesFilter')),
        );
    }

    /*
     * Converts camel case string to have spaces
     */
    public function convertCamelCaseToHaveSpacesFilter($camelCaseString)
    {

        $pattern = '/(([A-Z]{1}))/';
        return preg_replace_callback(
            $pattern,
            function ($matches) {return " " .$matches[0];},
            $camelCaseString
        );
    }

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

Where the function convertCamelCaseToHaveSpacesFilter will do the work if you pass it a camel case string.

In Twig page:

<body>
    {% set yourString = 'helloWorldHowAreYouDoing' %}
    {{ yourString|camelToSpace }}
</body>

This should also work for Pascal casing but it may require triming the string afterwards.

If autowiring is not enabled, remember to register your extension class. In services.yml:

services:
    app.twig_extension:
        class: RouteToExtensionClass\yourExtension
        public: false
        tags:
            - { name: twig.extension }
like image 74
Richard H Avatar answered Sep 12 '25 03:09

Richard H