单个视图中的多个属性凤凰
multiple attributes in a single view phoenix
我想要一个视图,但想根据调用它的 json-api 呈现不同的属性。例如:index页面不需要所有属性,所以不需要调用所有属性,而show page需要所有属性,所以应该获取所有属性。
我基本上想要这样的东西:
attributes [:id, :name, :email, :website, :inserted_at, :updated_at]
表演和
attributes [:id, :name, :email]
索引。
我正在为此使用 ja-serializer,所以只想要一个解决方案。
PS:我可以有两个具有相应属性的不同视图,但这似乎是一种解决方法也没有多大意义。
提前致谢。
如果您 post 一些代码会有所帮助。但是您可以在视图中执行此操作。您可以为每个控制器操作定义单独的 render
功能头。
例如:
def render("index.json", %{store: store}) do
%{data: %{store: %{id: store.sap_id, name: store.name}}}
end
def render("show.json", %{store: store}) do
%{data: %{store: %{id: store.sap_id, name: store.name, other: store.other}}}
end
在上面,每个动作都有一个渲染函数头:index
和 show
。然后函数体构建正确的 JSON 响应。您可以使用此方法自定义您想要的属性 return.
渲染方法调用中有一个可选参数。我们可以在 "fields" 中指定字段,并保持视图不变。
def index(conn, params) do
render("index.json-api", data: data, opts: [fields: %{"table_name"=> "fields,in,csv,style"}])
end
有关更多信息,请参阅中的条件属性包含
https://hexdocs.pm/ja_serializer/JaSerializer.DSL.html
我想要一个视图,但想根据调用它的 json-api 呈现不同的属性。例如:index页面不需要所有属性,所以不需要调用所有属性,而show page需要所有属性,所以应该获取所有属性。
我基本上想要这样的东西:
attributes [:id, :name, :email, :website, :inserted_at, :updated_at]
表演和
attributes [:id, :name, :email]
索引。
我正在为此使用 ja-serializer,所以只想要一个解决方案。
PS:我可以有两个具有相应属性的不同视图,但这似乎是一种解决方法也没有多大意义。
提前致谢。
如果您 post 一些代码会有所帮助。但是您可以在视图中执行此操作。您可以为每个控制器操作定义单独的 render
功能头。
例如:
def render("index.json", %{store: store}) do
%{data: %{store: %{id: store.sap_id, name: store.name}}}
end
def render("show.json", %{store: store}) do
%{data: %{store: %{id: store.sap_id, name: store.name, other: store.other}}}
end
在上面,每个动作都有一个渲染函数头:index
和 show
。然后函数体构建正确的 JSON 响应。您可以使用此方法自定义您想要的属性 return.
渲染方法调用中有一个可选参数。我们可以在 "fields" 中指定字段,并保持视图不变。
def index(conn, params) do
render("index.json-api", data: data, opts: [fields: %{"table_name"=> "fields,in,csv,style"}])
end
有关更多信息,请参阅中的条件属性包含 https://hexdocs.pm/ja_serializer/JaSerializer.DSL.html