elixir - 在 Phoenix 中渲染 JSON

标签 elixir phoenix-framework

我使用“mix phoenix.gen.json”生成渲染 json 的代码,结果如下图:

defmodule Pghm.SightingsView do    
  use Pghm.Web, :view

  def render("sighting.json", %{sighting: sighting}) do
    %{what: sighting.what,
      lat:  sighting.lat,
      long: sighting.long}
  end

  def render("index.json", %{sightings: sightings}) do
    %{data: render_many(sightings, Pghm.SightingsView, "sighting.json")}
  end

  def render("show.json", %{sighting: sighting}) do
    %{data: render_one(sighting, Pghm.SightingsView, "sighting.json")}
  end
end

但是,当我尝试访问调用它时,我收到:无法为 Pghm.SightingsView 呈现“sighting.json”,请为 render/2 定义匹配子句或在“web/templates/sightings”处定义模板。没有为此模块编译模板。
分配:

我所看到的所有地方都表明这应该有效,但我没有得到爱。

最佳答案

我今天就遇到了这个问题,这是因为我将 View 的名称复数了,就像在 Rails 中一样。

根据 Phoenix 源码 (1) 中的注释,key 是从 View 名称中推断出来的。

A collection is any enumerable of structs. This function returns the rendered collection in a list: render_many users, UserView, "show.html" is roughly equivalent to:


Enum.map(users, fn user ->
  render(UserView, "show.html", user: user)
end)

The underlying user is passed to the view and template as :user, which is inferred from the view name. The name of the key in assigns can be customized with the :as option



(1) https://github.com/phoenixframework/phoenix/blob/8a6beef9e13f049a8458db25b71fb70afae7673a/lib/phoenix/view.ex#L267

所以试试这个:
defmodule Pghm.SightingView do    
  use Pghm.Web, :view

  def render("sighting.json", %{sighting: sighting}) do
    %{what: sighting.what,
      lat:  sighting.lat,
      long: sighting.long}
  end

  def render("index.json", %{sightings: sightings}) do
    %{data: render_many(sightings, Pghm.SightingView, "sighting.json")}
  end

  def render("show.json", %{sighting: sighting}) do
    %{data: render_one(sighting, Pghm.SightingView, "sighting.json")}
  end
end

关于elixir - 在 Phoenix 中渲染 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38426829/

相关文章:

elixir - 如何使用 :observer. 启动我的应用程序?

date - 如何将 "YYYYMMDD"格式的字符串解析为 Timex.Parse.DateTime 类型?

Elixir [42] 打印为 '*'

linux - 在 RaspberryPI 上找不到 Erlang 包含目录

elixir - 在 Elixir Phoenix Absinthe GraphIQL 客户端中实现身份验证?

internationalization - I18n 分段路由器 Phoenix

websocket - Phoenix channel ,设置每个 channel 的最大用户数

ubuntu - 如何使用 upstart 可靠地管理 phoenix 应用程序

elixir - 为什么我的动态定义函数未定义?

oauth-2.0 - 如何要求登录 Elixir Phoenix 应用程序?