Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...