如何制作alpinejs“重新渲染” htmx交换后的组件

发布于 2025-02-10 21:45:15 字数 3451 浏览 3 评论 0原文

我正在尝试集成Django + Alpinejs + HTMX。一切进展顺利,除非我尝试交换一些已经是Alpinejs组件的一部分的HTML。

如果我仅在第二次交换后正确渲染组件呈现HTML。

例如
<div id="cart-row" x-data="{selectedOrderItem: {{item_id|default:'null'}} }">
    <div id="cart-holder">
        <table id="cart">
            <thead>
                <tr>
                    <th style="width: 10%">CANT</th>
                    <th>Product</th>
                    <th style="width: 15%">TOTAL</th>
                </tr>
            </thead>
            <tbody>
                {% for item in items %}
                <tr 
                    id="product{{item.product.id}}" 
                    :class="{ selectedOrderItem: selectedOrderItem == {{item.id}} }"
                    @click="selectedOrderItem = {{item.id}};"
                >
                    <td>{{item.quantity}}</td>
                    <td>{{item.product.name}}</td>
                    <td>{{item.get_price}}</td>
                </tr>
                {% endfor %}
        
            </tbody>
        </table>
    </div>
    <div id="right-menu">
        <div id="table-buttons" hx-swap-obb="true">
            {% for item in items %}
            <div class="" x-cloak x-show="selectedOrderItem == {{item.id}}">
                <button 
                    class="addButton"
                    hx-trigger="click" 
                    hx-target="#cart-row" 
                    hx-swap="outerHTML" 
                    hx-post="{% url 'add_to_cart' idOrder=order.id idProduct=item.product.id  %}?cartAction=1"
                > 
                    + {{item.id}}
                </button>
            </div>
            {% endfor %}
        </div>
    </div>

,如果我点击“添加到购物车”按钮,则交换了#cart-row div,但是:class =“ {selectedOrderItem:selectedOrderitem:selectionOrderItem == {{item.id} }}“绑定仅第二次起作用。就像Alpinejs没有意识到内容已交换。

有什么办法可以使整个组件“重新渲染 /重新定位”? 还是正确交换的正确方法是什么?

编辑:

查看
def add_to_cart(request, idOrder=None, idProduct=None):
    try:
        with transaction.atomic():
            selectedOrderItem, created = OrderItem.objects.get_or_create(order_id=idOrder, product_id=idProduct, defaults={'quantity': 1})
            if not created:
                selectedOrderItem.quantity += 1
                selectedOrderItem.save()

            items = OrderItem.objects.select_related().filter(order_id=idOrder)
            order = get_object_or_404(Order, pk=idOrder)



            elements = []
            # CART
            elements.append(
                render_to_string(
                    'rfidapp/partials/cart_row.html', 
                    request=request, 
                    context={
                        "order": order,
                        "items": items,
                        "selectedOrderItem": selectedOrderItem.id
                    }
                )
            )

            #OOB SWAP TO UPDATE THE TOTAL AT THE BOTTOM LEFT
            elements.append(
                render_to_string('rfidapp/partials/order_total.html', request=request, context={"order": order})
            )

        return HttpResponse("\n".join(elements))
    except Exception as e:
        return HttpResponseBadRequest(f"{e}")

I'm trying to integrate Django + AlpineJS + HTMX. All is going well, except when I try to swap some HTML that is already a part of a AlpineJS component.

If I swap the html the component renders correctly only after the second swap.

template
<div id="cart-row" x-data="{selectedOrderItem: {{item_id|default:'null'}} }">
    <div id="cart-holder">
        <table id="cart">
            <thead>
                <tr>
                    <th style="width: 10%">CANT</th>
                    <th>Product</th>
                    <th style="width: 15%">TOTAL</th>
                </tr>
            </thead>
            <tbody>
                {% for item in items %}
                <tr 
                    id="product{{item.product.id}}" 
                    :class="{ selectedOrderItem: selectedOrderItem == {{item.id}} }"
                    @click="selectedOrderItem = {{item.id}};"
                >
                    <td>{{item.quantity}}</td>
                    <td>{{item.product.name}}</td>
                    <td>{{item.get_price}}</td>
                </tr>
                {% endfor %}
        
            </tbody>
        </table>
    </div>
    <div id="right-menu">
        <div id="table-buttons" hx-swap-obb="true">
            {% for item in items %}
            <div class="" x-cloak x-show="selectedOrderItem == {{item.id}}">
                <button 
                    class="addButton"
                    hx-trigger="click" 
                    hx-target="#cart-row" 
                    hx-swap="outerHTML" 
                    hx-post="{% url 'add_to_cart' idOrder=order.id idProduct=item.product.id  %}?cartAction=1"
                > 
                    + {{item.id}}
                </button>
            </div>
            {% endfor %}
        </div>
    </div>

For example, if I hit the add to cart button, the #cart-row div is swapped, but the :class="{ selectedOrderItem: selectedOrderItem == {{item.id}} }" binding only works the second time. It's like AlpineJS doesn't realize that the content has been swapped.

Is there any way that I can make the whole component "re-render / re-initialize"?
Or what is the right way to do that swap?

EDIT:

view
def add_to_cart(request, idOrder=None, idProduct=None):
    try:
        with transaction.atomic():
            selectedOrderItem, created = OrderItem.objects.get_or_create(order_id=idOrder, product_id=idProduct, defaults={'quantity': 1})
            if not created:
                selectedOrderItem.quantity += 1
                selectedOrderItem.save()

            items = OrderItem.objects.select_related().filter(order_id=idOrder)
            order = get_object_or_404(Order, pk=idOrder)



            elements = []
            # CART
            elements.append(
                render_to_string(
                    'rfidapp/partials/cart_row.html', 
                    request=request, 
                    context={
                        "order": order,
                        "items": items,
                        "selectedOrderItem": selectedOrderItem.id
                    }
                )
            )

            #OOB SWAP TO UPDATE THE TOTAL AT THE BOTTOM LEFT
            elements.append(
                render_to_string('rfidapp/partials/order_total.html', request=request, context={"order": order})
            )

        return HttpResponse("\n".join(elements))
    except Exception as e:
        return HttpResponseBadRequest(f"{e}")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄意 2025-02-17 21:45:15

问题在于,您没有在HTMX请求中包含该Alpine.js组件(selectedOrderItem)的一个状态数据。因此,当HTMX交换整个组件时,它将在此过程中丢失selectordordem的值。我们需要将此变量发送到后端,并将其包括在模板中。向HTMX请求添加其他数据的最简单方法是在其上使用X-Model的隐藏输入元素进行同步数据,然后使用 hx-include 将其添加到请求中。将其放置在组件中的任何位置:

<input type="hidden" name="selected_order_item" x-model="selectedOrderItem">

并修改按钮:

<button 
    class="addButton"
    hx-trigger="click" 
    hx-target="#cart-row" 
    hx-swap="outerHTML"
    hx-include="[name='selected_order_item']" 
    hx-post="{% url 'add_to_cart' idOrder=order.id idProduct=item.product.id  %}?cartAction=1"
>

在后端,我们可以在request.post中访问它,例如:

context={
         "order": order,
         "items": items,
         "selectedOrderItem": request.POST.get("selected_order_item", "null")
}

之后在x-data中访问了所选的。订单项目将出现。

x-data="{selectedOrderItem: {{selectedOrderItem}} }"

The problem is that you are not including the one state data that this Alpine.js component is having (selectedOrderItem) in the HTMX request. So when HTMX swaps the whole component, it will lose the value of selectedOrderItem during the process. We need to send this variable to the backend and include it in the template. The easiest way to add additional data to the HTMX request is to use a hidden input element with x-model on it to sync data, and then use hx-include to add it to the request. Put this anywhere inside the component:

<input type="hidden" name="selected_order_item" x-model="selectedOrderItem">

And modify the button:

<button 
    class="addButton"
    hx-trigger="click" 
    hx-target="#cart-row" 
    hx-swap="outerHTML"
    hx-include="[name='selected_order_item']" 
    hx-post="{% url 'add_to_cart' idOrder=order.id idProduct=item.product.id  %}?cartAction=1"
>

At the backend now we can access it in request.POST, e.g.:

context={
         "order": order,
         "items": items,
         "selectedOrderItem": request.POST.get("selected_order_item", "null")
}

After that in the x-data the selected order item will appear.

x-data="{selectedOrderItem: {{selectedOrderItem}} }"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文