问题
i have a query result that will be used in view, but when i call the variable in view, i got undefined function data/0
(because data is not function)
i already pass data with different way, map, etc
controller.ex :
def new(conn, _params) do
data =
Enum.map(
from(AccountTypeSchema)
|> Repo.all(),
fn elem ->
elem |> Map.from_struct() |> Map.delete(:__meta__)
end
)
render(conn, "new.html", data: data)
end
view.html.eex :
<% Enum.each data, fn(item) -> %>
<option value="us">Facebook</option>
<% end %>
call data
variable from view
回答1:
Use this code instead:
render(conn, "new.html", account_types: data)
Then in view:
<% Enum.each @account_types, fn(item) -> %>
<option value="us">Facebook</option>
<% end %>
Generally you have @
prefixed variables available in template when you pass keyword list or map to a view: https://hexdocs.pm/phoenix/Phoenix.View.html#render/3
回答2:
Enum.map/2
returns a list (I took a responsibility to rewrite the code in more idiomatic way):
data =
AccountTypeSchema
|> Repo.all()
|> Enum.map(& &1 |> Map.from_struct() |> Map.delete(:__meta__))
Obviously one cannot access list by key; pass a keyword instead:
render(conn, "new.html", data: data)
来源:https://stackoverflow.com/questions/53940549/phoenix-pass-variable-to-view