Masatoshi Nishiguchi's Blog

Masatoshi Nishiguchi's Blog

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

  @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`.

      <%= application_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 application_title_tag(conn, assigns) do
    case get_page_title(conn, assigns) do
      nil ->
        live_title_tag(@site_name)

      page_title ->
        live_title_tag(page_title, suffix: " · " <> @site_name)
    end
  end

  defp get_page_title(conn, assigns) do
    cond do
      # live view
      assigns[:page_title] ->
        assigns.page_title

      # regular view
      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.

 
Share this