pallets / jinja

A very fast and expressive template engine.
https://jinja.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
10.25k stars 1.6k forks source link

rerender specific block without partials #1808

Closed scratchmex closed 1 year ago

scratchmex commented 1 year ago

Given the following template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>This is the title</title>
</head>
<body>
    <h1>This is a header</h1>
    {% block content %}
    <p>This is the magic number: {{ magic_number }}.</p>
    {% endblock %}
</body>
</html>

If you want to render only the content block, do:

rendered_html = env.get_template("mytemplate.html").render_block("content", magic_number=42)
"""
<p>This is the magic number: 42.</p>
"""

Which is basically something like this: https://github.com/sponsfreixes/jinja2-fragments

This is very useful with frameworks like htmx because you rerender a specific part of the template without having to split into multiple files and having a partials-mess

Another reference of why this might be useful is this essay Template Fragments - HTMX

I am open to submit a PR

davidism commented 1 year ago

To render a block manually:

t = env.get_template("index.html")
"".join(t.blocks["content"](t.new_context(magic_number=42)))

To render a macro manually:

t.module.content(magic_number=42)

I don't think we need to do anything else. jinja2-fragments looks great, I think there's another similar extension as well.