Phoenix其他布局变量,例如@inner [英] Phoenix additional layout variables like @inner
问题描述
我希望为布局添加其他 layout 参数,例如@inner
.例如,@title
代表<title>@title</title>
,单个区域代表onload javascript.
I am looking to add additional layout parameters like the @inner
for the layout. For example @title
for the <title>@title</title>
and an area for onload javascript for individual pages.
window.onload = function () {
@onload_js
}
这些是在布局中设置的,因此我不确定在Phoenix中处理这些的最佳方法.谢谢:D.
These are set in the layout, so I am not sure the best way to handle these in Phoenix. Thanks :D.
推荐答案
对于页面标题,您可以简单地从控制器中传递一个值:
For the page title, you can simply pass a value through from your controller:
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_title
或assigns.page_title
,因为如果分配中不存在:page_title
键,它们将出错.
Note that this uses assigns[:page_title]
instead of @page_title
or assigns.page_title
as they will error if the :page_title
key is not present in assigns.
对于包括模板(您的脚本示例),有 render_existing /3 (以及最新版本中相同功能的文档凤凰城).
For including templates (your script example) there is render_existing/3 (and the docs for the same function in the latest version of Phoenix).
该文档提供了一个与您所要求的示例类似的示例,为方便起见,我将其复制到此处:
The documentation gives a similar example to what you requested so I have copied it here for convenience:
请考虑以下情况:应用程序布局允许视图动态呈现文档头部中的一部分脚本标签.有些视图可能希望注入某些脚本,而另一些视图则不想.
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>
然后@inner视图的模块可以决定为脚本提供预编译的模板,还是直接实现该功能,即:
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
要使用预编译的模板,请在模板目录中为您要呈现的相应视图创建scripts.html.eex文件.例如,对于UserView,请在web/templates/user/中创建scripts.html.eex文件.
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/.
这篇关于Phoenix其他布局变量,例如@inner的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!