VaN
VaN

Reputation: 2210

Keep leading 0 in Twig

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 ?

Upvotes: 30

Views: 27816

Answers (3)

AlixB
AlixB

Reputation: 1238

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.

Upvotes: 11

javlae
javlae

Reputation: 81

Kinda late here, but ran into the same.

With twig 3.x you can use:

{{your.number | format_number({min_integer_digit:'2'})}}

Upvotes: 8

griotteau
griotteau

Reputation: 1822

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') }}

Upvotes: 53

Related Questions