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) }}
Easy.
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)