使用htmx WebSocket扩展时HTML元素被转义、标签注释的问题
htmx WebSocket扩展发送OOB内容时HTML标签被清理问题解决
问题概述
使用htmx WebSocket扩展实现玩家列表实时更新,后端发送带hx-swap-oob属性的<li>元素来追加玩家,但页面渲染时标签被清理,仅显示带引号的文本和注释,无法生成正常的<li>标签。
异常现象
发送的WebSocket消息:
<li id="player-list" hx-swap-oob="beforeend" type="1">player 2</ li>
页面实际渲染结果:
"player 2" <!-- li-->
文本被添加到了正确的<ol id="player-list">位置,但未被包裹在<li>标签内。
页面代码
<!DOCTYPE html> <html> <head> <script src="https://unpkg.com/htmx.org@1.9.8"></script> <script src="https://unpkg.com/htmx.org/dist/ext/ws.js"></script> <title>Hat Game: Your Room Code</title> <link rel="stylesheet" href="/stylesheets/style.css" /> </head> <body> <body> <h1>Your room code</h1> <p> Give this code to everyone in your group: <span id="room-code">RSTWAG</span>. </p> <p> As everyone enters the room code, you will see their names populate below. When your entire group is there, tap <b><em>Everybody's in</em></b >. </p> <div id="players-in-the-room"> <h2>Players in the room</h2> <ol id="player-list" hx-ext="ws" ws-connect="/ws-roster/?roomcode=RSTWAG"> <li type="1">fur</li> </ol> </div> <div id="ws-messages"></div> </body> </body> </html>
测试发送命令
aws --profile hat-game-prod apigatewaymanagementapi post-to-connection \ --data $(echo -n '<li id="player-list" hx-swap-oob="beforeend" type="1">player 2</ li>' | base64) \ --connection-id ${CONNECTION_ID} \ --endpoint-url https://qu3vq8riw2.execute-api.us-east-1.amazonaws.com/ws-roster
期望渲染结果
<ol id="player-list" hx-ext="ws" ws-connect="/ws-roster/?roomcode=RSTWAG"> <li type="1">fur</li> <li type="1">player 2</li> </ol>
问题根源与修复
- 闭合标签格式错误:发送的消息中
</ li>包含多余空格,htmx的HTML解析器无法识别这种不规范的闭合标签,导致标签被判定为无效内容。需改为标准的</li>。 - OOB目标指定错误:
hx-swap-oob属性需要明确指定目标元素的ID,格式为[操作]:#[目标ID]。你错误地将<li>的id设为player-list,导致htmx混淆了目标元素。正确的做法是移除<li>的id,将hx-swap-oob设为beforeend:#player-list。
修正后的WebSocket消息:
<li hx-swap-oob="beforeend:#player-list" type="1">player 2</li>
使用修正后的消息发送后,htmx会正确解析并将新的<li>元素追加到<ol id="player-list">的末尾,实现预期效果。
内容的提问来源于stack exchange,提问作者Doug Naphas
相关产品推荐
相关产品推荐

