# Generate page title from Phoenix LiveView module name


I want to update [HTML title](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title) every time users navigates in my [LiveView](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html) app. I just thought it would be convenient if I can generate a title from the module name.

[日本語版](https://qiita.com/mnishiguchi/items/99d57a40285db4311fd3)

According to [Phoenix LiveView documentation](https://hexdocs.pm/phoenix_live_view/live-layouts.html#updating-the-html-document-title), it is as easy as providing a title text to `socket.assigns[:page_title]`.

```elixir
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](https://hexdocs.pm/phoenix/Phoenix.Naming.html) module useful to achieve that.

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

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

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

```elixir
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](https://dev.to/mnishiguchi/phoenix-1-5-page-title-gdg) before so that I can configure site-wide title suffix.

I want to try [Internationalization (i18n)](https://en.wikipedia.org/wiki/Internationalization_and_localization) next.

That's it!

