我想在Phoenix的子视图/控制器中设置应用程序模板中的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
电话,但无法找到其在凤凰城等价的。
将属性传递给父子模板/视图的正确方法是什么?
这里有几个选项。我假设你想在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
将提高。
谢谢Gazler!我能够使用你对模板的推荐来解决这个问题,并且在控制器动作中为'render'调用添加'page_title:'标题''。 –
这篇文章涵盖了这一点:http://sevenseacat.net/2015/06/01/custom_page_titles_in_phoenix.html –
谢谢José!这非常有帮助! –
3个选项在这里展示:http://cloudless.studio/articles/27-implementing-page-specific-titles-in-phoenix –