Search code examples
htmlflaskhtmx

How can i exchange data between HTMX and flask in JSON or any thing other then html


So i am trying to make a app using Flask and HTMX. I know that htmx wants to get data as html to swap with the given target element, but is there a way to update the current page using other data such as dict. or a list or json coming from flask,

In short app.py:

@app.route("/someroute")
def test():
    data =[{"name":"test",....}....]
    return data

index.html

.
.
.
<input name="name"
            hx-get="/someroute" ... hx-target="result" />

.
.
.
<table>
<th>Name</th>
<tbody id='results'>
//Loops over the incoming data from flask and renders it as 
// <tr> <td>{{item.name}}</td>
</tbody>
</table>

i have tried send the html data directly and TBH its quite hectic to do all. I dont have issue with rendering somedata from html but when it comes to sending some update request to flask and then update the from end data accordingly its quite confusing, and i cant find any good documentation about this


Solution

  • I think the example you've provided is good reason why returning html is better.

    You can use render_template where you pass data in the context and return it as response.

    HTMX will inject the response inside #results.

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route("/someroute")
    def test():
        data = [{"name":"test",....}....]
        return render_template('table.html', data=data)
    

    Your table.html can then look like this

    {% for item in data %}
        <tr>
            <td>{{ item.name }}</td>
        </tr>
    {% endfor %}