Skip to content
This repository has been archived by the owner on May 8, 2024. It is now read-only.

Sorting when iterating #56

Closed
jaybrueder opened this issue Oct 16, 2017 · 3 comments
Closed

Sorting when iterating #56

jaybrueder opened this issue Oct 16, 2017 · 3 comments

Comments

@jaybrueder
Copy link

jaybrueder commented Oct 16, 2017

Hi,

I have a list of data objects and iterate over them like so:

{% for course_data in site.data.contentful.spaces.company.course %}
  {% assign title = course_data[1]['title'] %}

  <li>{{title}}</li>
{% endfor %}

This works great. However, the order in which the objects are listed depends on the ID value that each content object gets from Contentful.

These look like this for example:

ID: 1m3ap... Title: Open...
ID: 5kFqz... Title: Agile...
ID: UL3CJ... Title: Infrastructure...

Therefore, the list looks as follows:

  • Open
  • Agile
  • Infrastructure

What I would like is and alphabetical order:

  • Agile
  • Infrastructure
  • Open

Is there a way that I can bring order into the iteration?

Maybe I can use the title field as the ID of the object?
That would also solve this problem for me:
#57

@dlitvakb
Copy link
Contributor

Hi @jaybrueder,

There's the sort filter in Liquid, which allows you to sort collections by multiple keys in the objects present within that collection. For example, the following snippet orders a collection of posts by title:

{% for post in site.data.contentful.spaces.blog.posts | sort: 'title' %}
  <h1>{{post.title}}</h1>
{% endfor %}

That said, looks like your data may need some re-structuring, or you need to do some extra looping, as it looks that you're fetching the titles from objects nested in your course_data, and that's not accessible directly through the top level as my example shows.

You can learn more about Liquid filters here: https://help.shopify.com/themes/liquid/filters/array-filters

As for the ID issue, you can access it as if it were a hash key blog_post['123_my_weird_key'] instead of using the dot notation.

Cheers

@jaybrueder
Copy link
Author

Thank you for your help!

Organising the data into one YAML file makes this problem go away.
I am sorting the data like this now. Works like a charm.

{% assign sorted = site.data.contentful.spaces.company.course | sort: 'title' %}
      
{% for topic_data in sorted %}
   {% assign title = topic_data['title'] %}
   {% assign subheadline = topic_data['subheadline'] %}
      
   {% include course.html title=title subheadline=subheadline %}
{% endfor %}

@dlitvakb
Copy link
Contributor

That's great! Glad it worked out.

Cheers

@dlitvakb dlitvakb closed this as completed Aug 1, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants