phoenix pass variable to view

两盒软妹~` 提交于 2019-12-11 05:58:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!