Reverse Sort for MkDocs

Background

MkDocs doesn't have much information about how to do modify or create templates on its websites. As a result, I had to search around on the internet to figure out how to create templates for my website which is made with MkDocs.

After doing some digging on other websites, I found that MkDocs uses Jinja for the templating engine. From there, I was able to find some of the documentation on how to use the values and variables in a template.

Since I was creating a website with a blog, I wanted to sort the content by the most recent first. The problem with this is that using the for function, it would sort the content from oldest to newest. Again, I could not figure out how to reverse the order as this was not documented in the Jinja documentation where I could find it nor was it on Stack Overflow.

Out on a limb, I typed the below and believe it or not, it sorted the content in reverse order just like how I wanted it to.

{% for nav_item in nav | reverse %}
/// whatever you want to loop over
{% endfor %}

The Break Down

Let's break down the parts of the code.

Start The Loop

{% for

This denotes the beginning of the for loop. The space between the parenthesis and the word "for" is required. Otherwise the command will not be intepreted as you expect and thus not work.

Iterator Variable

nav_item

In this example, the "nav_item" is the name of the variable that is used within the for loop.

For those of you that are familiar with writing foreach loops in Java or C#, "i" is commonly used for this same purpose.

foreach(item in collection){
    // do something
}

"item" in the example above would be the same as "nav_item" in Jinja example.

Collection or Array

"nav" is the collection or array of items that will be looped over one by one. This variable can be changed to loop over other items that are available, such as page variables or configuration variables.

Reverse The Items

| reverse

This part of the command, will sort the items in the collection or array in reverse. If your items are sorted by date, then the most recent date would be first. If your items are sorted by alphabet, then the end of the alphabet ("Z") would be first.

Close The Loop

{% endfor %}

This closes the end of the for loop.

Conclusion

Hopefully this helps you if you encounter the same problem that I did.

Updated: 2020-07-15 | Posted: 2020-07-15
Author: Kenny Robinson