in Programming

Setting page title in Phoenix

In Rails, you probably used content_for  for setting every page title. In Phoenix, layout is rendered before page template is rendered so content_for  approach will not work. Instead, here’s how you can set different page title for every action.

In layout_view.ex file, add get_page_title  function:

def get_page_title(conn) do
  if conn.assigns[:page_title] do
    "#{conn.assigns[:page_title]} - ApplicationName"
  else
    "ApplicationName"
  end
end

In application’s layout file app.html.eex, add:

<title><%= get_page_title(@conn) %></title>

To set page title, just add assign page_title  to controllers action:

def index(conn, _params) do
  bar = "..."
  render conn, "index.html", page_title: "Index", foo: bar
end

If you set assign, it will display “Assign value – ApplicationName”. If assign is not set, it will just display “ApplicationName”.

You can also use |>  operator for cleaner code:

conn
|> assign(:page_title, "Index")
|> assign(:foo, bar)
|> render "index.html"

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.