如何制作alpinejs“重新渲染” htmx交换后的组件
我正在尝试集成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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,您没有在HTMX请求中包含该Alpine.js组件(
selectedOrderItem
)的一个状态数据。因此,当HTMX交换整个组件时,它将在此过程中丢失selectordordem
的值。我们需要将此变量发送到后端,并将其包括在模板中。向HTMX请求添加其他数据的最简单方法是在其上使用X-Model
的隐藏输入元素进行同步数据,然后使用hx-include
将其添加到请求中。将其放置在组件中的任何位置:并修改按钮:
在后端,我们可以在
request.post
中访问它,例如:之后在
x-data
中访问了所选的。订单项目将出现。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 ofselectedOrderItem
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 withx-model
on it to sync data, and then usehx-include
to add it to the request. Put this anywhere inside the component:And modify the button:
At the backend now we can access it in
request.POST
, e.g.:After that in the
x-data
the selected order item will appear.