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.

2 Answers 2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.