DEV Community

Masatoshi Nishiguchi
Masatoshi Nishiguchi

Posted on • Edited on

4 3

Generate page title from Phoenix LiveView module name

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

  ...
Enter fullscreen mode Exit fullscreen mode

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"
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 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!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay