gpt4 book ai didi

elixir - Phoenix : Having a JSON and HTML representation of the same resource

转载 作者:行者123 更新时间:2023-12-05 01:39:29 24 4
gpt4 key购买 nike

我开始在教程之外为一个小用例使用 Phoenix。到目前为止还不错,但我对以下内容有点吃惊。

我有一个资源“录音”,我想在 JSON 格式的/api/recordings 和带有模板的/recording 中访问,结果是 HTML。

理想情况下,Ecto 表示是唯一的,甚至 Controller 的一部分也可以共享?

现在我必须拥有 2 个资源 recordingAPI 和 recordingHTML,或者 2 个 Controller 和 1 个资源。

有什么例子吗?我一直在寻找一个或另一个,但找不到用于同一资源的 :api 管道和 :browser 管道。

谢谢

最佳答案

您可以利用 phoenix accepts 插件和两种不同 View /布局的组合

# router.ex
defmodule TestExWeb.Router do
use TestExWeb, :router

pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end

pipeline :api do
plug :accepts, ["json"]
end

scope "/", TestExWeb do
pipe_through :browser

get "/recording", PageController, :index
end

scope "/api", TestExWeb do
pipe_through :api

get "/recording", PageController, :index
end
end

如您所见,:browser 使用 :accepts ["html"]:api 使用 :accepts ["json"]。您可以在 conn 的私有(private)结构中找到它,并像这样在 Controller 中使用它:

defmodule TestExWeb.PageController do
use TestExWeb, :controller

def index(%{private: %{phoenix_format: format}} = conn, _params) do
data = "Hello World"

render(conn, "index.#{format}", data: data)
end
end

现在,您只需要告诉 phoenix 如何呈现您的 json,html 已经由布局中的 page.html.eex 处理,因此将以下内容添加到您的 page_view。例如

defmodule TestExWeb.PageView do
use TestExWeb, :view

def render("index.json", %{data: data}) do
%{
data: data
}
end
end

此解决方案的两个缺点:

  • 您需要在每个 Controller 中使用此格式片段(也许您可以在“发送”响应后使用插件来规避此问题)
  • 你正在使用 phoenix 的内部变量

关于elixir - Phoenix : Having a JSON and HTML representation of the same resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com