4

I have a number field used for episode numbers and I would like to automatically add a leading zero when the number is less than 10. I have this working with a conditional but it seems inefficient. Is there a twig filter that I don't know about that does this?

{% if entry.episodeNumber < "10" %}
    {% set episodeNumber = '0' ~ entry.episodeNumber %}
{% else %}
    {% set episodeNumber = entry.episodeNumber %}
{% endif %}

The above works but seems overly long to accomplish what should be a simple task.

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
CreateSean
  • 1,973
  • 16
  • 34

2 Answers2

7

There aren't any filters built in to Craft (or Twig) that does this, but your {% if %} conditional could be trimmed down to a single-line ternary operation:

{% set episodeNumber = (entry.episodeNumber < 10 ? '0') ~ entry.episodeNumber %}

or even

<span>{{ (entry.episodeNumber < 10 ? '0') ~ entry.episodeNumber }}</span>
Mats Mikkel Rummelhoff
  • 22,361
  • 3
  • 38
  • 69
6

You can use PHP's sprintf function via [the format filter in Twig].1

So to add a leading zero to single digit numbers:

{{ "%02d"|format('4') }}

Which would return 04


Or in your case {{ "%02d"|format(entry.episodeNumber) }}

James Greig
  • 837
  • 4
  • 14