微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。