Magik.JsonView (Magik v0.10.0) View Source

Render a struct to a map with given options

  • fields: which fields are extract directly from struct
  • custom_fields: which fields are render using custom render_field/2 function
  • relationships: 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

Link to this function

render_custom_fields(struct, view \\ nil, fields)

View Source

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])
Link to this function

render_fields(structs, fields)

View Source
Link to this function

render_json(struct, view, opts)

View Source
Link to this function

render_relationship(struct, field, view)

View Source
Link to this function

render_relationships(struct, relationships)

View Source

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")
}
Link to this function

render_template(struct, view, template)

View Source