Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Terkwood/b29cae052322706b3272748f7fe50974 to your computer and use it in GitHub Desktop.
Save Terkwood/b29cae052322706b3272748f7fe50974 to your computer and use it in GitHub Desktop.
Phoenix Content Negotiation
# Controller option 1, implicit render selected based on format
defmodule MyApp.UserController do
use Phoenix.Controller
def show(conn, %{"id" => id}) do
render conn, :show, user: Repo.get(User, id)
end
end
# Controller option 2, explicit render with format pattern match
defmodule MyApp.UserController do
use Phoenix.Controller
def show(conn, %{"id" => id, "format" => "html"}) do
render conn, "show.html", user: Repo.get(User, id)
end
def show(conn, %{"id" => id, "format" => "json"}) do
render conn, "show.json", user: Repo.get(User, id)
end
def show(conn, %{"id" => id, "format" => "xml"}) do
render conn, "show.xml", user: Repo.get(User, id)
end
end
# View
defmodule MyApp.UserView do
use MyApp.View
def render("show.json", %{user: user}) do
%{
name: user.name,
email: user.email
}
end
def render("show.xml", %{user, :user} do
XMLBuilder.build(user)
end
# render("show.html", ...) defined by show.html.eex template automatically
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment