htmx:如何用 hx-swap-oob 交换表行?

问题描述

我想用 hx-swap-oob 替换现有页面“带外”的表格行。

在浏览器中:

<table>
 <tr id="offer_1">....</tr>
 <tr id="offer_2">....</tr> (old)
 <tr id="offer_3">....</tr>
</table>

从服务器到客户端:

<table hx-swap-oob="outerHTML:#offer_2" hx-select="#offer_2">
 <tr id="offer_2"> .... </tr> (new)
</table>

但到目前为止,这是结果:

<table>
 <tr id="offer_1">....</tr>
 <table hx-swap-oob="outerHTML:#offer_2" hx-select="#offer_2">
  <tr id="offer_2"> .... </tr> (new)
 </table>
 <tr id="offer_3">....</tr>
</table>

我猜当 htmx 从服务器获取代码段时,hx-select 不会得到评估。

如何在带外交换一行?

解决方法

这确实有效:

 <tr hx-swap-oob="true" id="offer_2"> .... </tr> (new)

但它有一个缺点:

您需要修改创建此行的方法。根据您的上下文,您可能已经有了一种方法。为什么要修改这个方法,仅仅因为这个方法的结果应该被带外使用?

如果您使用 Django,则可以使用此代码段在创建 HTML 后添加 hx-swap-oob 属性:

def add_oob_attribute(html):
    """
    I would like to avoid this ugly hack
    https://github.com/bigskysoftware/htmx/issues/423
    """
    assert isinstance(html,SafeString)
    new,count = re.subn(r'(<\S+)',r'\1 hx-swap-oob="true"',html,count=1)
    if not count == 1:
        raise ValueError(f'Could not add hx-swap-oob: {html}')
    return mark_safe(new)

我创建了一个问题,以便将来找到更好的解决方案:

https://github.com/bigskysoftware/htmx/issues/423