1
votes

I'm creating a chat app and I have a bunch of channel messages. Here's one of them:

def handle_in("read", %{ "chat_id" => chat_id }, socket) do
  user_id = socket.assigns[:id]

  ts = DateTime.utc_now
  case ChatManager.mark_as_read({user_id, chat_id, ts}) do
    {:ok, chat_user} ->
      last_read_at_unix = chat_user.last_read_at |> TimeConverter.ecto_to_unix
      {:reply, {:ok, %{ chat_id: chat_id, last_read_at: last_read_at_unix }}, socket}
    {:error, changeset} ->
      {:reply, {:error, %{errors: changeset.errors}}, socket}
  end
end

Can I use phoenix Views to separate my presentation / response logic? This way I can just quickly go to a view file and see what is returned by each message.

1
Yes, you can use Phoenix views in your channels. Just call MyView.render ....Steve Pallen

1 Answers

3
votes

Phoenix Views are just normal modules with functions in them.

You can either call those functions directly:

MyApp.Web.ChatView.render("message.json", %{message: my_message})

Or use a Phoenix.View function which would call the render/2 function of your view:

Phoenix.View.render_one(MyApp.Web.ChatView, "message.json", message: my_message)

The Phoenix.View functions have a few advantages if your arguments are more dynamic (for example if you pass nil as the message).

Consult the Phoenix.View documentation for details on those convenience functions.

When building a large application, it makes sense to have .json templates for all your models because you'll need to pass json around in API responses, as channel messages or serialized messages in a message queue. The views you've already written are reusable for all of those cases.