7

I originally asked this on Stack Overflow, but I'm hoping for more response here.

In Craft, I'm trying to order entries by the title. Each title is a number, but the sort function handles it like a string. Because of that 100 shows up before 2, 31 before 4, and so on.

{% for entry in craft.entries.section('mySection').order('title').find() %}
    <h2>§{{entry.title}}</h2>
{% endfor %}

Is there a way to do this without extending twig?

  • I see that you've ask this question before, over on main stackoverflow. Did you try the answer there using natsort? Question with natsort answer – Nicolaides Jun 12 '14 at 13:55
  • Yes, as mentioned in my question I originally asked this on stack overflow. I would like to know is if there is a way to do this without extending twig. – Spoeken Jun 12 '14 at 13:59
13

You can do that using MySQL’s cast() function:

craft.entries.section('mySection').order('cast(title as unsigned)')

Alternatively, you might get better performance if you create an actual Number field called “numberTitle”, attach it to your Entry Type, and set the Entry Type’s title to be dynamically generated using the template “{numberTitle}”. Then you can just order by that field instead:

craft.entries.section('mySection').order('numberTitle')
| improve this answer | |
  • That 2nd technique is interesting, but where exactly do you set that template for the title field? Can I set templates for other fields too? – carlcs Jun 12 '14 at 15:04
  • 2
    See buildwithcraft.com/docs/… – Brandon Kelly Jun 12 '14 at 15:07
4

Twig doesn't have a natsort() filter.

But I've put together a simple plugin which extends the sort-filter:

https://github.com/victor-in/Craft-TwigBetterSort

| improve this answer | |

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.