Phoenix 1.6 Page Title

mnishiguchi

Masatoshi Nishiguchi

Posted on February 13, 2021

Phoenix 1.6 Page Title

I made a custom awesome_title_tag view helper function because I wanted to support both controller views and live views.

View

In lib/mnishiguchi_web/views/layout_view.ex

defmodule MnishiguchiWeb.LayoutView do
  use MnishiguchiWeb, :view

  @site_name "Mnishiguchi"
  def site_name(), do: @site_name

  def awesome_title_tag(conn, assigns) do
    live_title_tag(page_title(conn, assigns) || @site_name, suffix: " 路 #{@site_name}")
  end

  # live view
  defp page_title(_conn, %{page_title: page_title} = _assigns) do
    page_title
  end

  # controller view
  defp page_title(conn, assigns) do
    if function_exported?(view_module(conn), :page_title, 2) do
      view_module(conn).page_title(view_template(conn), assigns)
    else
      @site_name
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

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" %>
+  <%= awesome_title_tag(@conn, assigns) %>
Enter fullscreen mode Exit fullscreen mode

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.

馃挅 馃挭 馃檯 馃毄
mnishiguchi
Masatoshi Nishiguchi

Posted on February 13, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related