Skip to main content

Command Palette

Search for a command to run...

Generate page title from Phoenix LiveView module name

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

More from this blog

Raspberry Pi TensorFlow Liteで物体検出を楽しむ

この記事について Raspberry Pi、TensorFlow、Pythonのいずれにも詳しくない筆者が、物体検出をやって楽しんだ成果の記録です。 TensorFlow公式の物体検出のサンプルプログラムを実行します。 動作環境 ボード Raspberry Pi 4 Model B OS Raspberry Pi OS (32-bit または 64-bit) デスクトップ環境 カメラ Raspberry Pi カメラモジュール v2 Python Python ...

Apr 23, 20231 min read

Elixir Circuits.I2C with Mox

This is written in Japanese. I might convert it to English later, maybe. はじめに Elixirのテストでモックを用意するときに利用するElixirパッケージとして、moxが人気です。Elixir作者のJosé Valimさんが作ったからということもありますが、ただモックを用意するだけではなくElixirアプリの構成をより良くするためのアイデアにまで言及されているので、教科書のようなものと思っています。 一言でいうと「その場...

Dec 3, 20213 min read
M

Masatoshi Nishiguchi's Blog

62 posts