2015-07-20 75 views
9

我想在Phoenix的子視圖/控制器中設置應用程序模板中的title標籤。在Phoenix的父視圖/模板中設置屬性

title標籤是web/templates/layout/app.html.eex模板裏面,但我有一個ArticlesController這使得在<%= @inner %>從Rails的產品我用yield電話,但無法找到其在鳳凰城等價的。

將屬性傳遞給父子模板/視圖的正確方法是什麼?

+3

這篇文章涵蓋了這一點:http://sevenseacat.net/2015/06/01/custom_page_titles_in_phoenix.html –

+0

謝謝José!這非常有幫助! –

+0

3個選項在這裏展示:http://cloudless.studio/articles/27-implementing-page-specific-titles-in-phoenix –

回答

8

這裏有幾個選項。我假設你想在rails中使用類似content_for的東西。

一種選擇是使用render_existing/3http://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將提高。

+1

謝謝Gazler!我能夠使用你對模板的推薦來解決這個問題,並且在控制器動作中爲'render'調用添加'page_title:'標題''。 –