Search code examples
djangodjango-templateshtmx

htmx insert multiple table rows


I'm using Django, if that makes any difference. Anyway, I have this tbody element in my template:

            <tbody
               id="log-stream-table-body"
               hx-get="{% url 'pages:log_stream_rows' %}?last_ts={{ last_log_ts }}"
               hx-trigger="every 30s"
               hx-target="this"
               hx-swap="afterbegin"
            >
               {% include "pages/_home_log_stream_rows.html" with log_stream=log_stream %}
            </tbody>

The url it's pointing to returns this template snippet (which is actually pages/_home_log_stream_rows.html used in the include above):

{% for log in log_stream %}
    <tr>
        <td>{{ log.ts|date:"Y-m-d H:i:s.u" }}</td>
        <td>{{ log.process }}</td>
        <td>{{ log.source }}</td>
        <td>{{ log.message }}</td>
    </tr>
{% endfor %}

<div
    id="log-stream-hyperscript"
    hx-swap-oob="outerHTML"
    data-log-ts="{{ last_log_ts }}"
></div>

The problem is that I'm returning multiple tr elements at the top level, so the whole thing just fails.

I can wrap it in a <template> tag, and it works, but of course then nothing is visible. Wrapping in anything else (div, andother tbody) just breaks the display in different ways.

How can I group these multiple tr elements so that htmx adds them in correctly at the top of my table?


Solution

  • I don’t understand why HTMX behaves this way, but I got it to work with the response looking like this, i.e. using oob-swaps for both things:

    <tbody hx-swap-oob="afterbegin:#log-stream-table-body">
        <tr>
            <td>{DateTime.Now}</td>
            <td>1</td>
            <td>{r.Next()}</td>
        </tr>
        <tr>
            <td>{DateTime.Now}</td>
            <td>2</td>
        </tr>
        <tr>
            <td>{DateTime.Now}</td>
            <td>3</td>
        </tr>
    </tbody>
    
    <div id="log-stream-hyperscript"
         hx-swap-oob="outerHTML"
         data-log-ts="{DateTime.Now}">{DateTime.Now}</div>
    
    

    (This is test data using ASP.Net Core, I don’t have a Python/Django server here)

    Using the latest HTMX 2.0.0, but not sure that’s relevant.