使用 websockets 渲染模板

Rendering templates using websockets

不知道有没有办法在通过websockets添加内容时渲染凤凰模板?如果我想使用 websockets 添加一些复杂的 html 结构作为模板而不在 javascript 代码中复制此结构,该怎么办?

我看到的唯一方法是在控制器中生成模板 html,如下所示:

def create(conn, params) do
  #some code
  Endpoint.broadcast!("user_room:123", "new_comment", %{comment_content: MyApp.PostView.render(conn, "comment.html", comment: comment)})
  #some code
end

然后将此生成的内容添加到处理通道响应的 javascript 文件中的页面。

我还没有尝试过,所以它甚至可能不起作用,但我想知道是否有更合适的方法来做到这一点?如果可以的话?

对于这样的任务,你基本上有两个选择:

  1. 在服务器端渲染 HTML 并通过 websockets 发送它,这就是您想要做的
  2. 在客户端渲染HTML,所以你只需要通过websockets发送数据
如果您想使用 Phoenix 模板,

MyApp.PostView.render(conn, "comment.html", comment: comment)} 是处理此问题的完美方法,这是上述第一种情况。

不要忘记它 returns {:safe, html} 而不仅仅是 HTML,所以您可能希望使用 render_to_string 通过 websockets 发送它。

第二种处理方法的优点是发送的数据较少,但您将无法轻松地重用模板,因此这取决于您的要求和应用程序。