0

Symfony twig

How to add space following capital letters only when it is following small letters.

{{ 'IWantHTML'|humanize }} //displays 'I want h t m l'. // it should be 'I want HTML'.

The other thing is it makes everything small letters following the first letter. e.x.

{{ 'IWantHTML'|humanize }} // should be 'I Want HTML'.
{{ 'i_want_html'|humanize}} // should be 'I want html'.
{{ 'CustomerPickSale2'|humanize}} // should be 'Customer Pick Sale2'.
Archi
  • 485
  • 3
  • 12

3 Answers3

2

Below custom twig filter works!!

new Twig_SimpleFilter('readable', array($this, 'readableFormat'))

 /**
 * @param $string
 * @return mixed
 */
public function readableFormat($string)
{
    $match_filter = array(
        '/(?<!\ )[A-Z][a-z]+/',
        '/(?<!\ )[A-Z][A-Z]+/',
    );

    $Words = preg_replace($match_filter, ' $0', trim($string));
    return str_replace('_', ' ', $Words);
}

{{ 'IWantHTML'|readable }} // I Want HTML
{{ 'i_want_html'|readable|ucfirst }} // I want html
{{ 'CustomerPickSale2'|readable|ucfirst }} // Customer Pick Sale2
Archi
  • 485
  • 3
  • 12
-1

This is the snippet of humanize filter :

function humanize($str) {
    $str = trim(strtolower($str));
    $str = preg_replace('/[^a-z0-9\s+]/', '', $str);
    $str = preg_replace('/\s+/', ' ', $str);
    $str = explode(' ', $str);
    $str = array_map('ucwords', $str);
    return implode(' ', $str);
}

and you can see it does not do what you want.So you have to implement your own filter How to Write Twig Extentions and how to create Custom Twig Fitler

Yuseferi
  • 7,931
  • 11
  • 67
  • 103
  • That doesn't look right. If that's the code for humanize it wouldn't do what it's doing right now. I know how to write twig extension, I just need to know how to accomplish this. – Archi Jan 09 '18 at 17:37
  • @Archi, want to do something with humanize which is humanize not for that. the only solution for you need is custom extension or custom pre preprocess you data in you're controller – Yuseferi Jan 09 '18 at 18:46
  • I was looking for code on a custom filter. The code you provided above is not even the code for humanize filter. I am not sure from where did you get that. – Archi Jan 09 '18 at 20:13
-1

I suggest you this Twig Extensions

Imanali Mamadiev
  • 2,604
  • 2
  • 15
  • 23