Last active
August 8, 2021 17:10
-
-
Save chrismccord/31340f08d62de1457454 to your computer and use it in GitHub Desktop.
Phoenix Content Negotiation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
NM, figure it out