【问题标题】:phoenix: render template of other folderphoenix:其他文件夹的渲染模板
【发布时间】:2020-05-25 07:31:50
【问题描述】:

我的 web/templates 文件夹中有两个模板文件夹:

> ls web/templates
personal_info       user

我想要的是在personal_info 的另一个视图中呈现user 文件夹中的一些模板。所以我在路径上有一个文件:web/templates/personal_info/index.html.eex,我有以下内容:

<%= render "user/xyz.html" %>

但我收到以下错误:

[error] #PID<0.821.0> running MyApp.Endpoint terminated
Server: localhost:4000 (http)
Request: GET /
** (exit) an exception was raised:
    ** (Phoenix.Template.UndefinedError) Could not render "user/xyz.html" for MyApp.PersonalInfoView, please define a matching clause for render/1 or define a template at "web/templates/personal_info". The following templates were compiled:

* index.html

请告诉我如何渲染在其他文件夹中定义的模板,我尝试了几种排列,但都没有奏效。

【问题讨论】:

标签: templates web-deployment elixir phoenix-framework


【解决方案1】:

Phoenix 模板只是函数,所以当你想从PersonalInfo 的视图中渲染UserView 的“xyz.html”模板时,只需调用函数!

假设您在web/templates/personal_info/show.html.eex 模板中。 (Phoenix.View.render 已经为您导入):

<%= render UserView, "xyz.html", user: user %>

如果您想传递所有模板指定您的 PersonalInfo 模板已提供:

<%= render UserView, "xyz.html", assigns %>

正如您所发现的,这在任何地方都有效,因为模板只是函数。例如,同样的事情可以在 iex 中工作:

iex> Phoenix.View.render(MyApp.UserView, "xyz.html")
"<h1>User ..."

【讨论】:

  • 在 Phoenix 1.3.0 上,我必须将 alias MyApp.UserView 添加到 web/views/personal_info_view.ex 中,否则它会显示为 (module UserView is not available
  • @owyongsk 这个文件现在在哪里?看起来它在 phoenix 1.3.0 之后不再存在?
【解决方案2】:

截至凤凰1.5.1

Phoenix 按名称匹配控制器、视图和模板。可以通过put_view更改,比如:

conn
  |> put_view(MyAppWeb.SpecialView)
  |> render(:show, message: "Hello")

https://hexdocs.pm/phoenix/Phoenix.Controller.html#render/3-views

【讨论】:

  • 就是这样! :)
【解决方案3】:

对我来说,当我指定应用程序名称时工作:

web/templates/product_gallery/index.html.eex:

<p>Please, render me!</p>

web/templates/kitchen/index.html.eex:

<%= render APP.ProductGalleryView, "index.html", assigns %>

如果我尝试在没有应用程序名称的情况下进行渲染,我会得到:

undefined function ProductGalleryView.render/2 (module ProductGalleryView is not available)

【讨论】:

  • 在你的lib/web/views/kitchen_view.ex中,你也可以添加alias APP.ProductGalleryView这样你就可以使用render ProductGalleryView
【解决方案4】:

我在 Phoenix 1.3.0 上。看来我必须添加

alias MyApp.Userview

web/views/personal_info_view.ex,然后

<%= render conn, UserView, "xyz.html" %>

没有上面的别名,那么你必须

<%= render conn, MyApp.UserView, "xyz.html" %>    

【讨论】:

    【解决方案5】:

    显然以下工作:

    <%=  Phoenix.View.render(MyApp.UserView, "xyz.html") %>
    

    如果有更好的选择,请告诉我。

    来源:this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多