-
-
Save jeregrine/22a178657572d21e4b98 to your computer and use it in GitHub Desktop.
This file contains 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
defmodule MyApp.CommentView do | |
use MyApp.Web, :view | |
@attributes ~W(id name inserted_at) | |
def render("show.json", %{data: comments}) when is_list(comments) do | |
for comment <- comments do | |
render("show.json", data: comment) | |
end | |
end | |
def render("show.json", data: comment) do | |
comment | |
|> Map.take(@attributes) | |
|> Map.put(:user, UserView.render('show_lite.json', data: data.user) | |
end | |
end |
This file contains 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
defmodule MyApp.MyModelView do | |
use MyApp.Web, :view | |
@attributes ~W(id body title inserted_at) | |
def render("show.json", %{data: my_model}) | |
my_model | |
|> Map.take(@attributes) | |
|> Map.update!(:title, &String.capitalize) | |
|> Map.put(:user, UserView.render("show.json", data: my_model.user) | |
|> Map.put(:comments, CommentView.render("show.json", data: my_model.comments) | |
end | |
end |
This file contains 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
defmodule MyApp.UserView do | |
use MyApp.Web, :view | |
@attributes ~W(id name inserted_at) | |
def render("show.json", %{data: user}) | |
render("show_lite.json", data: user) | |
|> Map.put(:image, ImageView.render("show.json", data: user.image) | |
end | |
def render("show_lite.json", data: user) | |
user | |
|> Map.take(@attributes) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great examples. You need to add
a
modifier to@attributes
list to make it work withMap.take
method. It accepts only list of atoms, not strings as it is in your example. Please update your post, because it on the top of "phoenix json views" query searches in search engine.Best regards