Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep leading 0 in Twig

Tags:

twig

symfony

In my database, I have a field containing the following data : 000010 (the type is integer)

In my twig tpl, I want to display it, then I do : {{ spending.documentName }}

But the browser displays "10". As if Twig was automaticcaly performing a trim on my data. I tried {{ spending.documentName|raw }} but it doesn't work. I dont find anything on Google about how to keep leading 0 with Twig.

Does anyone know how to proceed ?

like image 604
VaN Avatar asked Aug 06 '14 12:08

VaN


3 Answers

I think you must force the format (as your type is integer).

You can use the format filter :

{{ "%06d"|format(spending.documentName) }}

Or better create a twig extension (http://symfony.com/doc/current/cookbook/templating/twig_extension.html):

public function strpad($number, $pad_length, $pad_string) {
    return str_pad($number, $pad_length, $pad_string, STR_PAD_LEFT);
}

It's clearer in your template :

{{ spending.documentName | strpad(6,'0') }}
like image 53
griotteau Avatar answered Nov 10 '22 10:11

griotteau


You need to use the format filter.

Since placeholders follows the sprintf() notation, you should be able to convert sprintf('%06d', $integer); in PHP to {{ '%06d'|format($integer) }} in Twig.

like image 37
AlixB Avatar answered Nov 10 '22 08:11

AlixB


Kinda late here, but ran into the same.

With twig 3.x you can use:

{{your.number | format_number({min_integer_digit:'2'})}}
like image 4
javlae Avatar answered Nov 10 '22 08:11

javlae