NoDisplayName
NoDisplayName

Reputation: 15736

Rendering templates using websockets

I wonder if there is a way to render phoenix templates when adding content via websockets? What is the way to go if I want to add some complicated html structure that I have as a template using websockets without duplicating this structure in the javascript code?

The only way to do it that I see is to generate the template html in the controller with something like this:

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

and then add this generated content to the page in the javascript file handling the channel response.

I havent tried it yet so it may not even work but I wonder if there is a more proper way to do that? If it's possible in the first place?

Upvotes: 3

Views: 409

Answers (1)

Daniel Perez
Daniel Perez

Reputation: 6903

For such a task, you have basically two choices:

  1. Render the HTML on the server side and send it through websockets, which is what you are trying to do
  2. Render the HTML on the client side, so you only need to send data through websockets

MyApp.PostView.render(conn, "comment.html", comment: comment)} is a perfect way to handle this if you want to use your Phoenix templates, which is the first case describe above.

Do not forget that it returns {:safe, html} and not only the HTML though, so you will probably want to use render_to_string to send it through websockets.

The second way to handle this has the advantage of sending less data, but you will not be able to reuse your templates as easily, so it depends on your requirements and your application.

Upvotes: 3

Related Questions