Hi !
I’ve got a problem that I can’t find a solution for…
I’ve got a website site with differents articles entries that are all childrens of the “home” page.
On the website, I would like them to be sorted by a custom date field defined in the blueprint of articles as “header.datearticle”.
At first, I tried to do this in the template :
{% for post in page.find('/home').children.published.order('header.datearticle', 'desc') %}
[Some code]
{% endfor %}
But it didn’t work, because "header.datearticle’ return a string instead of a date object, and that my dates are dd-mm-yyyy hh:mm, so the ordering is not good.
I tried to do something like {% for post in page.find('/home').children.published.order('post.header.datearticle|date("U")', 'desc') %}
to change the date to unix time, but it seems that the order function doesn’t accept this like this.
Then I thought that maybe I should have change the blueprint of home to ask to change the order of children with something like
content:
order:
by: header.datearticle
dir: asc
But it doesn’t change anything and I don’t know why. Should “Folder Numeric Prefix” be removed before applying custom order like this ? (I did remove it also, but didn’t change anything).
Rather than using Grav’s limited sort operation which is designed for simple header values (not expressions based on them), maybe try Twig’s sort filter instead. Something like:
{% for post in page.find('/home').children|sort(post.header.datearticle|date("U"))|reverse %}
I think that should work. I added Twig’s reverse filter because sort doesn’t seem to support a direction parameter.
That’s an excellent idea, I think it should work, but I can’t manage to : /
If I use exactly what you wrote I get an error : An exception has been thrown during the rendering of a template ("Undefined index: post").
If I remove “post”, or even “post.header”, it doesn’t seems to work at all. Even switch from with “|reverse” or without doesn’t have any effect. I guess it’s what happened if the sort function doesn’t apply well ?
So, I found a solution, not the most elegant but it seems to work.
I kept my previous {% for post in page.find('/home').children.published.order('header.datearticle', 'desc') %}
And I changed the blueprint of articles to save the date in the format Y-m-d instead of d-m-Y. This way, even if it orders strings, it’s ok.
It was obvious to me that the date format was the whole problem. I didn’t even even bother mentioning it because I got the impression from your question that this was something out of your control or difficult to change.