Phoenix 1.5 Page Title

I do not like Phoenix's default behavior of the page title. I want it to be:

  • "Hello · Masatoshi Nishiguchi" when the title is "Hello"
  • "Masatoshi Nishiguchi" (default title) when the title is unspecified

Also I want to support both regular views and live views.

Template

In /lib/mnishiguchi_web/templates/layout/root.html.leex

   <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
   <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
   <%= csrf_meta_tag() %>
-  <%= live_title_tag assigns[:page_title] || "Home", suffix: " · Masatoshi Nishiguchi" %>
+  <%= live_title_tag page_title(@conn, assigns) %>

View

In lib/mnishiguchi_web/views/layout_view.ex

defmodule MnishiguchiWeb.LayoutView do
  use MnishiguchiWeb, :view

  @site_name "Masatoshi Nishiguchi"

  @doc """
  Adds a page title for both live views and regular views.
  """
  def page_title(conn, assigns) do
    cond do
      # For a live view, define `page_title/1` function in a live view file.
      #
      #     # lib/mnishiguchi_web/live/example_live.ex
      #     def page_title(assigns), do: "Example Live"
      #
      function_exported?(assigns[:live_module], :page_title, 1) ->
        apply(assigns[:live_module], :page_title, [assigns])

      # For a regular view, define `page_title/2` function in a view file.
      #
      #     # lib/mnishiguchi_web/views/example_view.ex
      #     def page_title("index.html", assigns), do: "Example Index Page"
      #
      function_exported?(view_module(conn), :page_title, 2) ->
        apply(view_module(conn), :page_title, [view_template(conn), assigns])

      true ->
        nil
    end
    |> format_page_title()
  end

  defp format_page_title(title) do
    case title do
      nil -> @site_name
      "" -> @site_name
      _ -> "#{title} · #{@site_name}"
    end
  end
end

Resources

Because of breaking changes between Phoenix 1.4 and 1.5, many examples out there did not work with Phoenix 1.5.

Here are some resources I referenced:

That's it.