Zero-padding (and other things) a string with the Twig template engine

This might sound a bit “duh” when you come to the conclusion but I did have to search for it and couldn’t find an immediate answer.

I want to zero-pad a month variable to always be 2 digits long, using the Twig template engine

Twig doesn’t actually have a built-in filter for this.

{{month|pad('0+',2)}} doesn’t exist.

However, Twig does have a filter called format that gives you access to the power of sprintf.

You can zero-pad the month variable by creating a format string and passing your month value as a parameter to the format filter, like so:

{{ "%02d"|format(month) }}


Because this gives you access to the whole set of sprintf format options you can use it to format you variables to just about anything.

Maybe I’m building a website for geeks who would appreciate selecting a month from a list of hexadecimal zero padded values.. {{ "%02X"|format(month)}}

(hopefully not)

6 comments on “Zero-padding (and other things) a string with the Twig template engine

  1. tzi

    Salut ! Sympa l’astuce ^^ Tu peux aussi créer un filtre twig pour ça. Ce sera un peu plus simple à comprendre un an plus tard :

        new \TwigSimpleFilter('strpad', function($input, $padlength, $padstring='', $padtype=STRPADRIGHT){
            return strpad($input, $padlength, $padstring, $pad_type);

    1. bendog

      Merci, c’est un excellente idée, plus facile a lire en effet.

      (for the non-french, read the code, it’s pretty explicit :)

  2. Xavier P

    Merci pour l’astuce !

  3. dootzky

    thank you dude! it worked beautifully! :)

    have a great day! ^_^

  4. Anna Filina

    You can also use sprintf like this directly in your Twig file: {{ “%05d”|format( }}

    Bonne journée.

  5. Artem

    Thanks, just what i was looking for!


Leave a Reply

Your email address will not be published. Required fields are marked *