凤凰:渲染其他文件夹的模板

Sau*_*abh 20 templates elixir web-deployment phoenix-framework

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

> ls web/templates
personal_info       user
Run Code Online (Sandbox Code Playgroud)

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

<%= render "user/xyz.html" %>
Run Code Online (Sandbox Code Playgroud)

但我得到以下错误:

[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
Run Code Online (Sandbox Code Playgroud)

请告诉我如何渲染在其他文件夹中定义的模板,我尝试了几个排列,但没有一个工作.

Chr*_*ord 33

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

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

<%= render UserView, "xyz.html", user: user %>
Run Code Online (Sandbox Code Playgroud)

如果您想传递提供PersonalInfo模板的所有模板分配:

<%= render UserView, "xyz.html", assigns %>
Run Code Online (Sandbox Code Playgroud)

正如您所发现的,这可以在任何地方使用,因为模板是Just Functions.例如,同样的事情在iex中起作用:

iex> Phoenix.View.render(MyApp.UserView, "xyz.html")
"<h1>User ..."
Run Code Online (Sandbox Code Playgroud)

  • 在Phoenix 1.3.0上,我不得不将`别名MyApp.UserView`添加到`web/views/personal_info_view.ex`中,否则它会说``(模块UserView不可用) (3认同)