7

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

For example:

1st
2nd
3rd
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];
    }
}
  • For the record, I had to Google what an ordinal suffix was. – Brad Bell Jul 17 '15 at 18:15
  • So did I Brad... – Peter Tell Jul 17 '15 at 18:35
  • Sorry about that. What should I have called it? – Katrin Jul 17 '15 at 19:24
  • 1
    I'm sure that's the right word... just got to learn something new is all. :) – Brad Bell Jul 17 '15 at 19:24
  • And thanks Brad, I'll try find some time figuring out how to add a plugin :) – Katrin Jul 17 '15 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 %}
  • Thanks Brandon. Is the an advantage/disadvantage to using a macro over a plugin? – Katrin Jul 23 '15 at 23:14

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.