Skip to content

Allow including single blocks from another template #634

@avsaase

Description

@avsaase

I use askama with htmx and like using the block fragments feature to generate partials from a single larger template. This is a nice feature because it keeps the HTML of (a large part of) the page together while still being able to generate partial responses for htmx to swap into the page. IMO this is cleaner than having separate templates for each partial that you include in the parent template, especially without good LSP support with "go to definition", etc. This approach is also recommended by htmx in their documentation.

This works great when returning a single partial but when using out-of-band swaps you often want to respond with several partials. It would be really convenient if you could include a single block from another template into a template that holds all the partials to be returned.

Here's a contrived example of what I want to achieve (htmx attributes omitted for clarity). The main template defines serveral blocks:

{# templates/index.html #}

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Home</title>
</head>
<body>
    {%- block value_block %}
    <p>Value: {{ value }}</p>
    {%- endblock %}

    {%- block length_block %}
    <p>Length: {{ length }}</p>
    {%- endblock %}
</body>
</html>

The partial template includes the blocks from the main template with some made up syntax:

{# templates/partial.html #}

{% include "index.html" block value_block %}
{% include "index.html" block length_block %}
use askama::Template;

#[derive(Template)]
#[template(path = "home.html")]
struct HomeTemplate {
    value: String,
    length: usize,
}

#[derive(Template)]
#[template(path = "partial.html")]
struct PartialTemplate {
    value: String,
    length: usize,
}

Rendering PartialTemplate would yield (ignoring white space differences):

<p>Value: some value</p>
<p>Length: 10</p>

This is effectively the opposite of defining the HTML of the partial in a separate template and including it into the main template. It keeps the HTML of the page together while still allowing to return multiple partials in a single response without having to concatenate several template renderings.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions