我使用“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/