I'd like to add an ordinal suffix to the loop.index
variable within a for
loop.
For example:
1st
2nd
3rd
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];
}
}
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 %}