Peter R
Peter R

Reputation: 3506

Phoenix Views - Adding an options arg to View render/ 2, Issue with overriding render/3

Why do I get this error, when trying to add a param to a view render/2 method.

def render("show.json", %{post: post}), do: render("show.json", %{post: post}, [user: true, room: true])
def render("show.json", %{post: post}, opts) do
  %{
    # stuff
    user: if(Keyword.fetch!(opts, :user), do: render_one(post.user, App.UserView, "show.json"), else: nil),
  }
end

Error:

imported Phoenix.View.render/3 conflicts with local function

I assume if I’m conflicting with an importing function, that this is a bad thing to do. Is there a better way to pass options, or can I somehow fix this in another way?

Upvotes: 0

Views: 804

Answers (1)

Justin Wood
Justin Wood

Reputation: 10041

In Elixir, you can have functions with the same name, but different arity in different modules. This is why in our views, we can define functions called render with an arity of 2. render/2 is the Erlang and Elixir convention for showing this.

With that said, Phoenix.View defines a render/3 function. Which is imported in all views. So the Elixir compiler sees that you are defining a function with the same name and arity as a function that is imported into the module and complains.

The only real solution here would be to not call your function render. A suggested name could be render_with_options.

Upvotes: 1

Related Questions