Magik.JsonView (Magik v0.10.0) View Source
Render a struct to a map with given options
fields
: which fields are extract directly from structcustom_fields
: which fields are render using customrender_field/2
functionrelationships
: a list of {field, view_module} defines which fields are rendered using another view
Here is a sample view
defmodule MyApp.PostView do
use JsonView
@fields [:title, :content, :excerpt, :cover]
@custom_fields [:like_count]
@relationships [author: MyApp.AuthorView]
def render("post.json", %{post: post}) do
# 1st way if `use JsonView`
render_json(post, @fields, @custom_fields, @relationships)
# 2nd way same as above
JsonView.render_json(post, __MODULE__,
fields: @fields,
custom_fields: @custom_fields,
relationships: @relationships
)
# 3rd render manual
post
|> JsonView.render_fields(@fields)
|> Map.merge(JsonView.render_custom_fields(post, __MODULE__, @custom_fields))
|> Map.merge(JsonView.render_relationships(post, @relationships))
end
def render_field(:like_count, item) do
# load like_count from some where
end
end
Link to this section Summary
Functions
Render field with custom render function
View module must defines render_field/2
function to render each custom field
Render relationship field for struct. relationships
is a list of {field, view} for mapping render.
For each field, call function View.render()
to render json for relation object.
Link to this section Functions
Render field with custom render function
View module must defines render_field/2
function to render each custom field
use JsonView
def render_field(:is_success, item) do
item.state > 3
end
render_custom_fields(struct, __MODULE__, [:is_success])
Render relationship field for struct. relationships
is a list of {field, view} for mapping render.
For each field, call function View.render()
to render json for relation object.
Example relationships:
relationships = [comments: CommentView, author: UserView]
Result of render_relationships(post, relationships)
equal to output of below code
%{
comments: CommentView.render_many(comments, CommentView, "comment.json"),
autho: UserView.render_one(author, UserView, "user.json")
}