elixir - Phoenix中渲染函数的区别

标签 elixir phoenix-framework

我试图了解不同 render 之间的区别 Phoenix 的功能。具体来说,我注意到有几个不同的 render Phoenix View 和 Phoenix 模板中的函数。

例如,在 Phoenix Controller 中,通常会看到以下内容:

# assume this is UserController
def index(conn, _params) do
    users = Repo.all(Users) # let's assume that this gives you all your users
    render conn, "index.html", users: users
end

index.html与此 View 关联的模板(即 UserView),您可以看到如下内容:
# index.html
<ul>
    <%= for user <- @users do %>
        <li><%= render "user.html", user: user %></li>
    <% end %>
</ul>

# user.html
<p><%= @user.name %></p>

我的理解是render index.html 内部的函数模板被编译为 render UserView 内部的函数.此外,在 iex 中挖掘之后,好像是render UserController 中的函数的索引 Action 来自 Phoenix.Controller.render/3 .

但是,我注意到在默认的 app.html.eex 里面在模板文件中,有一个如下所示的渲染函数:
<%= render @view_module, @view_template, assign %>

这似乎与之前渲染函数的签名不匹配。任何人都可以帮助解释此渲染的来源以及它是如何工作的吗?

最佳答案

Phoenix.View 有描述性文档,如果仍有疑问,还有 Phoenix.View.render/3 的源代码和 Phoenix.Controller.render/{1,3,4} 手上。

文档中的相关引用:

This inner representation allows us to render and compose templates easily. For example, if you want to render JSON data, we could do so by adding a “show.json” entry to render/2 in our view:

defmodule YourApp.UserView do
  use YourApp.View    
  def render("show.json", %{user: user}) do
    %{name: user.name, address: user.address}
  end
end

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

相关文章:

transactions - Ecto:在一笔事务中增加变更集

elixir - 为什么禁止在 guard 内使用远程功能

postgresql - Elixir Ecto 查询抛出 `Protocol not implemented Error`

elixir - 生成phoenix数据库图

ruby-on-rails - 从 Rails 到 Phoenix 共享身份验证/数据?

mongodb - docker-compose mongodb phoenix,[错误]无法连接:**(Mongo.Error)tcp连接:连接被拒绝-:econnrefused

elixir - 如何在 <%= for %> View 助手中增加 ID

elixir - 编译错误 - User.__struct__/1 未定义,无法扩展 struct User

elixir - 如何使用 Elixir 中的苦艾酒在查询中的嵌套项目上使用参数?

elixir - 如何在Phoenix布局中定义多个 "yield :something"?