Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
695 views
in Technique[技术] by (71.8m points)

elixir - Phoenix - controller with multiple render

Trying to create an app with Elixir + Phoenix, that would be able to handle both "browser" and "api" requests to handle its resources.

Is it possible to do it without having to do something like that :

scope "/", App do
  pipe_through :browser

  resources "/users", UserController
end

scope "/api", App.API as: :api do
  pipe_through :api

  resources "/users", UserController
end

which would mean having to create two controllers, which might have the same behavior, except that it will render HTML with the browser pipeline and, say JSON, for the api pipeline.

I was thinking maybe something like the Rails respond_to do |format| ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Gazler said, you are probably best served by having separate pipelines, but something like this can be pleasantly done with pattern matching on the same controller actions:

def show(conn, %{"format" => "html"} = params) do
  # ...
end

def show(conn, %{"format" => "json"} = params) do
  # ...
end

Or if the function bodies are the same, and you would only like to render a template based on the accept headers, you can do:

def show(conn, params) do
  # ...

  render conn, :show
end

Passing an atom as the template name will cause phoenix to check the accept headers and render the .json or .html template.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...