Masatoshi Nishiguchi
Masatoshi Nishiguchi's Blog

Masatoshi Nishiguchi's Blog

Generate page title from Phoenix LiveView module name

Masatoshi Nishiguchi's photo
Masatoshi Nishiguchi
·Apr 17, 2021·

2 min read

I want to update HTML title every time users navigates in my LiveView app. I just thought it would be convenient if I can generate a title from the module name.

日本語版

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

  ...

The problem is solved and it is more than good enough. But I was curious if I can generate the page title based on module name. I found Phoenix.Naming module useful to achieve that.

MnishiguchiWeb.EnvironmentLive
|> Phoenix.Naming.resource_name("Live")
|> Phoenix.Naming.humanize()
# "Environment"

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

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

  ...

I know it is not really necessary, but one benefit is that now I can copy and paste that snippet when making a live view without needing to come up with a 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!

 
Share this