hx-swap-oob 创建重复的 dom 元素?

问题描述 投票:0回答:1

我有这个工作流程:

  1. 新记录正在插入数据库
  2. 使用 HTMX,插入的行应该显示在表中(整个表被重新渲染)
  3. 与上一步同时,一定数量应该显示在段落元素中(段落被重新渲染)。

我尝试在段落元素上使用

hx-swap-oob="true"
参数来实现此目的,但问题是 DOM 元素(段落)由于某种原因被重复。有人可以告诉我为什么会发生这种情况以及如何解决这个问题吗?

模板.html

<table class="ui celled table">
    <thead>
        <tr>
            <th>Col 1</th>
            <th>Col 2</th>
            <th>Col 3</th>
        </tr>
    </thead>
    <tbody hx-post="{% url 'books' book.id %}" hx-trigger="addBook from:body" hx-vals='{"action": "show_editions"}' id="book_list">
        {% include "selling-books.html" %}
    </tbody>
</table>
...
... # some other DOM elements
...
<p id="book_number">{{ book.number }}</p>

销售书籍.html

{% for edition in editions %}
<tr>
    <td>{{ edition.in }} pieces</td>
    <td>{{ edition.out }} pieces</td>
    <td>{{ edition.price }} USD</td>
</tr>
{% endfor %}

<p hx-swap-oob="true" id="book_number">{{ book.number }}</p>

视图.py

def book_status(request, template_name = 'book.html', id=""):
    book = Book.objects.get(id=id)
    editions = Edition.objects.filter(book_id=id)

    if request.method == "POST":
            action = request.POST.get('action')
            
            if action == 'addBook':
                addEdition_form = AddBookForm(request.POST or None)
                if addEdition_form.is_valid():
                    ... some logic ...
                    
                    return HttpResponse(status=204, headers={'HX-Trigger': 'addBook'})

            if action == 'show_editions':
                for edition in editions:
                    ... some logic ...
                return render(request, 'selling-book.html', {'editions': editions, 'book': book})
    
    else:
        return render(request, template_name, {'book':book, 'editions':editions, 'addEdition_form': addEdition_form})   
django swap htmx
1个回答
0
投票

您可以通过检查模板中是否存在

addEdition_form
变量来避免重复。

替代解决方案可能是将表格内容和反段落拆分为单独的模板。

© www.soinside.com 2019 - 2024. All rights reserved.