pallets / flask

The Python micro framework for building web applications.
https://flask.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
68k stars 16.21k forks source link

Jinja2 Templating render_block to support HTMX #5243

Closed odie5533 closed 1 year ago

odie5533 commented 1 year ago

Hi! I would like to suggest adding a render_block function to templating.py to support rendering a defined Jinja2 template block. This would work like:

<body>
    <h1>This is a header</h1>
    {% block content %}
    <p>This is the magic number: {{ magic_number }}.</p>
    {% endblock %}
</body>
from flask import Flask, render_template, render_block

app = Flask(__name__)

@app.get("/full_page")
def full_page():
    return render_template("page.html.jinja2", magic_number=42)

@app.get("/only_content")
def only_content():
    return render_block("page.html.jinja2", "content", magic_number=42)

The purpose of this change is to support HTMX-style templates where you are returning partial HTML pages in Flask responses. Flask-native way to accomplish this is with multiple files (page.html and partial.html) and render_template('partial.html').

I then discovered jinja2-fragment which has a Flask function that simplifies this by adding the above-suggested functionality as a separate library (albeit small).

But this change is pretty small - one function - and so I would suggest upstreaming it here into Flask itself since I think this would offer a clear and simple solution to a common issue when working with HTMX. I'm happy to work on the PR if this issue is accepted.

This functionality is similar to Go's Template.ExecuteTemplate function which operates on named {{ block "name-here" .}} elements embedded in html templates.

Related Jinja2 ticket https://github.com/pallets/jinja/issues/1808

render_block code exists in the jinja2-fragments repo as well as the Jinja2 ticket.

Community Scope

Hundreds of Flask devs have starred https://github.com/mikeckennedy/jinja_partials and https://github.com/sponsfreixes/jinja2-fragments Flask is a popular choice for HTMX since it has first-rate Jinja2 integration. So I think supporting this change would be very welcome.

davidism commented 1 year ago

jinja-partials and jinja2-fragments already cover this, no need to add it to Flask at this time.