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!
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With