DEV Community

loading...

page title for Phoenix LiveView

mnishiguchi profile image Masatoshi Nishiguchi ・2 min read

I want to update HTML title every time users navigates in my LiveView app. I put together what I learned in this topic.

日本語版

According to Phoenix LiveView documentation, it is as easy as providing a title text to socket.assigns[:page_title].

defmodule MnishiguchiWeb.EnvironmentLive do
  use MnishiguchiWeb, :live_view

  def mount(_params, _session, socket) do
    socket = assign(socket, page_title: "Environment")
    {:ok, socket}
  end

  ...
Enter fullscreen mode Exit fullscreen mode

Problem is solved here and it is more than good enough. But I was curious if I can generate the page title based on module name. For that purpose, I found Phoenix.Naming module useful.

iex> MnishiguchiWeb.EnvironmentLive |> Phoenix.Naming.resource_name("Live") |> Phoenix.Naming.humanize()
"Environment"
Enter fullscreen mode Exit fullscreen mode

So I made a simple utility function that wraps Phoenix.Naming operations.

defmodule MnishiguchiWeb.LiveUtils do
  @doc """
  Generates a page title string based on the specified LiveView module atom.

  ## Examples

      iex(1)> LiveUtils.page_title(MnishiguchiWeb.Environment)
      "Environment"

      iex(2)> LiveUtils.page_title(MnishiguchiWeb.Environment.Measurements)
      "Measurements"

  """
  def page_title(view_atom) when is_atom(view_atom) do
    view_atom
    |> Phoenix.Naming.resource_name("Live")
    |> Phoenix.Naming.humanize()
  end
end
Enter fullscreen mode Exit fullscreen mode

Then I can use it in my live views.

defmodule MnishiguchiWeb.EnvironmentLive do
  use MnishiguchiWeb, :live_view

  @default_assigns [
    page_title: MnishiguchiWeb.LiveUtils.page_title(__MODULE__),
  ]

  def mount(_params, _session, socket) do
    socket = assign(socket, @default_assigns)
    {:ok, socket}
  end

  ...
Enter fullscreen mode Exit fullscreen mode

I know it is not really necessary, but the benefit is that now I can copy and paste that section of code to make another live view without the need to determine the page title.

There might be cleaner approaches but I am happy with this nice and simple solution.

Speaking of page title, I have written this other function before so that I can configure site-wide title suffix.

I want to try Internationalization (i18n) next.

That's it!

Discussion (0)

pic
Editor guide