我想title
从 Phoenix 的子视图/控制器中设置应用程序模板中的标签。
title
标签在模板内web/templates/layout/app.html.eex
,但我有一个ArticlesController
渲染到<%= @inner %>
来自 Rails 的我会使用yield
调用,但在 Phoenix 中找不到它的等价物。
将属性从其子级传递给父级模板/视图的正确方法是什么?
我想title
从 Phoenix 的子视图/控制器中设置应用程序模板中的标签。
title
标签在模板内web/templates/layout/app.html.eex
,但我有一个ArticlesController
渲染到<%= @inner %>
来自 Rails 的我会使用yield
调用,但在 Phoenix 中找不到它的等价物。
将属性从其子级传递给父级模板/视图的正确方法是什么?
您在这里有几个选择。我假设你想要像content_for
在rails中的东西。
一种选择是使用render_existing/3
http://hexdocs.pm/phoenix/0.14.0/Phoenix.View.html#render_existing/3
另一种灵活的方法是使用插头:
defmodule MyApp.Plug.PageTitle do
def init(default), do: default
def call(conn, opts) do
assign(conn, :page_title, Keyword.get(opts, :title)
end
end
然后在你的控制器中你可以做
defmodule FooController do
use MyApp.Web, :model
plug MyApp.Plug.PageTitle, title: "Foo Title"
end
defmodule BarController do
use MyApp.Web, :controller
plug MyApp.Plug.PageTitle, title: "Bar Title"
end
在你的模板中;
<head>
<title><%= assigns[:page_title] || "Default Title" %></title>
</head>
在这里,我们使用assigns
而不是@page_title
因为@page_title
如果未设置该值将引发。