7

I'd like to add an ordinal suffix to the loop.index variable within a for loop.

For example:

1st
2nd
3rd

2 Answers 2

5

You'd want to write a plugin that added an |ordinal Twig filter.

Then from your template, you would do: loop.index|ordinal.

The logic in the plugin would look something like:

public function ordinal($number)
{
    $ends = array('th','st','nd','rd','th','th','th','th','th','th');

    if ((($number % 100) >= 11) && (($number % 100) <= 13))
    {
        return $number.'th';
    }
    else
    {
        return $number.$ends[$number % 10];
    }
}
7
  • For the record, I had to Google what an ordinal suffix was.
    – Brad Bell
    Jul 17, 2015 at 18:15
  • So did I Brad...
    – Peter Tell
    Jul 17, 2015 at 18:35
  • Sorry about that. What should I have called it?
    – Katrin
    Jul 17, 2015 at 19:24
  • 1
    I'm sure that's the right word... just got to learn something new is all. :)
    – Brad Bell
    Jul 17, 2015 at 19:24
  • And thanks Brad, I'll try find some time figuring out how to add a plugin :)
    – Katrin
    Jul 17, 2015 at 19:25
7

This can also be done with a Twig macro, rather than creating a plugin:

{% macro ordinal(number) %}
    {%- spaceless %}
    {% if ((number % 100) >= 11) and ((number % 100) <= 13) %}
        {{ number }}th
    {% else %}
        {% set ends = ['th','st','nd','rd','th','th','th','th','th','th'] %}
        {{ number ~ ends[number % 10] }}
    {% endif %}
    {% endspaceless -%}
{% endmacro %}

{% from _self import ordinal %}

{% for entry in craft.entries %}
    <li>{{ ordinal(loop.index) }}</li>
{% endfor %}
1
  • Thanks Brandon. Is the an advantage/disadvantage to using a macro over a plugin?
    – Katrin
    Jul 23, 2015 at 23:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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