Phoenix 1.5 Page Title

I made a custom application_title_tag view helper function because I did 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. Here is what I did.

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" %>
+  <%= application_title_tag(@conn, assigns) %>

View

In lib/mnishiguchi_web/views/layout_view.ex

defmodule MnishiguchiWeb.LayoutView do
  use MnishiguchiWeb, :view

  @site_name "Masatoshi Nishiguchi"

  def site_name, do: @site_name

  def application_title_tag(conn, assigns) do
    page_title = fetch_page_title(conn, assigns)

    if page_title do
      live_title_tag(page_title, suffix: " · " <> @site_name)
    else
      live_title_tag(@site_name)
    end
  end

  defp fetch_page_title(conn, assigns) do
    cond do
      # For live view, we specify the title to `assigns[:page_title]`.
      assigns[:page_title] ->
        assigns.page_title

      # For regular view, we specify the title by defining `page_title/2`.
      #
      #     # lib/mnishiguchi_web/views/example_view.ex
      #     def page_title("index.html", assigns), do: gettext("Example Index Page")
      #
      function_exported?(view_module(conn), :page_title, 2) ->
        apply(view_module(conn), :page_title, [view_template(conn), assigns])

      true ->
        nil
    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.