Masatoshi Nishiguchi
Masatoshi Nishiguchi's Blog

Masatoshi Nishiguchi's Blog

Phoenix 1.6 Page Title

Masatoshi Nishiguchi's photo
Masatoshi Nishiguchi
·Feb 12, 2021·

2 min read

I made a custom app_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.


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


In lib/mnishiguchi_web/views/layout_view.ex

defmodule MnishiguchiWeb.LayoutView do
  use MnishiguchiWeb, :view

  @site_name "Masatoshi Nishiguchi"

  @doc """
  A title tag for the application. It supports both regular views and live views.
  When a title is unspecified, the title will fall back to the site name.

      # When title is "Blog"
      "Blog · My site name"

      # When title is unspecified
      "My site name"

  ## Usage

  It is typically used in `lib/example_web/templates/layout/root.html.leex`.

      <%= app_title_tag(@conn, assigns) %>

  ### Title for a regular view

  Specify the title in `assigns[:page_title]`.

      socket = assign(socket, page_title: "Sales dashboard")

  ### Title for a live view

  Define `page_title/2` in a view file.

      def page_title("index.html", assigns), do: "Home page"

  def app_title_tag(conn, assigns) do
    case get_page_title(conn, assigns) do
      @site_name -> live_title_tag(@site_name)
      page_title -> live_title_tag(page_title, suffix: " · " <> @site_name)

  # live view
  defp get_page_title(conn, %{page_title: page_title} = _assigns), do: page_title

  # regular view
  defp get_page_title(conn, assigns) do
    if function_exported?(view_module(conn), :page_title, 2) do
      view_module(conn).page_title(view_template(conn), assigns)


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.

Share this