0

我想使用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>

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

如何在带外交换一行?

4

1 回答 1

0

这确实有效:

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

但它有一个缺点:

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

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

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

于 2021-03-17T11:56:33.370 回答