How to use variables coming from a for loop inside another category for loop?

{% for paper in include.datapath %}
  <div id="{{paper.category}}" class="modal">
    <div class="modal-content">
      <ul>
      {% for post in site.categories[paper.category] %}
      <li>{{ post.title }}</li>
      {% endfor %}
      </ul>
    </div>
  </div>
{% endfor %}  

Here is the code! Here paper.category is coming from a data file. And I want that to sort my posts by category. But it’s not working! Thank you

You will want to assign the variable first, so your code will look like this:

{% assign papers = collection.products | sort: 'category' %}

{% for paper in papers %}
  <div id="{{paper.category}}" class="modal">
    <div class="modal-content">
      <ul>
      {% for post in site.categories[paper.category] %}
      <li>{{ post.title }}</li>
      {% endfor %}
      </ul>
    </div>
  </div>
{% endfor %}  

Using assign gives you an array, then you can apply filters, like sort, join, etc. Here is some good documentation on array filters: