Skip to content

Instantly share code, notes, and snippets.

@jeregrine
Forked from paulcsmith/comment_view.ex
Created March 18, 2015 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeregrine/22a178657572d21e4b98 to your computer and use it in GitHub Desktop.
Save jeregrine/22a178657572d21e4b98 to your computer and use it in GitHub Desktop.
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
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
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
@mciastek
Copy link

Great examples. You need to add a modifier to @attributes list to make it work with Map.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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment