Phoenix 额外的布局变量,如@inner

Phoenix additional layout variables like @inner

我希望为布局添加额外的 layout 参数,例如 @inner。例如 @title 用于 <title>@title</title> 和用于加载的区域 javascript 用于单个页面。

window.onload = function () {
   @onload_js
}

这些是在布局中设置的,所以我不确定在 Phoenix 中处理这些的最佳方式。谢谢 :D.

对于页面标题,您可以简单地从您的控制器传递一个值:

def edit(conn, params) do
  render(conn, "edit.html", page_title: "Edit The Thing")
end

<head>
  <title><%= assigns[:page_title] || "Default Title" %></title>
</head>

请注意,这使用 assigns[:page_title] 而不是 @page_titleassigns.page_title,因为如果 :page_title 键不存在于赋值中,它们将出错。


为了包含模板(您的脚本示例),有 render_existing/3 (and the docs for the same function in the latest version of Phoenix).

该文档提供了一个与您要求的类似的示例,因此为了方便起见,我将其复制到此处:

Consider the case where the application layout allows views to dynamically render a section of script tags in the head of the document. Some views may wish to inject certain scripts, while others will not.

<head>
  <%= render_existing view_module(@conn), "scripts.html", assigns %>
</head>

Then the module for the @inner view can decide to provide scripts with either a precompiled template, or by implementing the function directly, ie:

def render("scripts.html", _assigns) do
  "<script src="...">"
end

To use a precompiled template, create a scripts.html.eex file in the templates directory for the corresponding view you want it to render for. For example, for the UserView, create the scripts.html.eex file at web/templates/user/.