Calmcode - htmx: hello world

Hello HTMX

1 2 3 4 5 6 7

In this video we will assume this Flask app:

import random

from flask import Flask, render_template

app = Flask(__name__, template_folder="templates")


@app.route("/")
def index():
    return render_template("01-index.html")


@app.route("/update-content")
def update_content():
    random_number = random.randint(1, 100)
    return f"<p>Updated content: Random number is {random_number}</p>"


if __name__ == "__main__":
    app.run(debug=True)

This app assumes that there is a folder called templates with an 01-index.html file that looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/htmx.org"></script>
</head>
<body>
    <button hx-get="/update-content" hx-target="#content">Update Content</button>
    <div id="content">
        <p>Want a random number there?</p>
    </div>
</body>
</html>

Note the <script src="https://unpkg.com/htmx.org"></script> tag on top. This loads HTMX and adds all the behavior that we are interested in.

This app will generate a random number every time you click the "Update Content" button. The way it works is that the button has an hx-get attribute that points to the /update-content endpoint. When you click the button, HTMX will make a GET request to that endpoint and replace the content of the #content div with the HTML that is returned. The neat thing here is that we are not returning JSON, instead we are returning HTML directly. This means that we can use any backend language we like to generate the HTML (Python) and that we do not need to worry about writing any Javascript.

This is a simple example, but the next few videos will become more and more elaborate.