在 Phoenix parent view/template 中设置属性

Setting properties in parent view/template in Phoenix

我想在 Phoenix 的 child view/controller 应用程序模板中设置 title 标签。

title 标签位于 web/templates/layout/app.html.eex 模板内,但我有一个 ArticlesController 呈现给 <%= @inner %> 来自 Rails 我会使用 yield 调用,但在 Phoenix 中找不到它的等价物。

将属性从其 child 传递到 parent template/view 的正确方法是什么?

这里有几个选项。我假设你想要 rails 中的 content_for 之类的东西。

一种选择是使用 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会增加