Search code examples
pythonhtmlajaxflaskhtmx

How to do infinite scrolling with flask? (htmx or other methods)


this is the code that gets post information. ive seen a few things on stackoverflow but none of them really address a core example of infinite scrolling with htmx.

                    {% for post in  get_feed_posts(session['username'])  %}
                      {% if post[7] != "off" %}
              
                          {% from 'macros.html' import post_block %}
                          {{ post_block(post) }}
                      {%endif%}
                    
                    {%endfor%}
            
                    </div>

update: this wont run the test route

DATA = [{"name":"Neil"},{"name":"Corie"}]

def get_data(page=0, pagesize=1):
  print(DATA[pagesize * page: pagesize*page + pagesize])
  return DATA[pagesize * page: pagesize*page + pagesize]

@app.route('/test', methods=['POST', 'GET'])
def test():
  data = get_data(page=request.args.get("page", 0, type=int))
  return render_template("test.html", data=data)

-- html

<tr hx-get="/test/?page=0"
 hx-trigger="revealed"
 hx-swap="afterend">
 <td>Agent Smith</td>
 <td>[email protected]</td>
 <td>55F49448C0</td>
 </tr>

Solution

  • If you look at https://htmx.org/examples/infinite-scroll/ , you'll see that it sends GET requests to the server with a page=n query parameter, when the user scrolls down the page, so your server should return a new "page" of html data

    on your flask server then:

    @app.get("/some-route")
    def some_route():
      data = get_data(page=request.args.get("page", 0, type=int))
      return render_template("my-template.html", data=data)
    

    where your get_data() function returns different data, depending on the page number

    this is usually done using SQL Alchemy. Here's an example: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination

    but you could also just use a list like:

    DATA = [{"name":"Neil"},{"name":"Corie"}, ....]
    
    def get_data(page=0, pagesize=20):
      return DATA[pagesize * page: pagesize*page + pagesize]