LoginSignup
0

More than 1 year has passed since last update.

Phoenix LiveViewのページタイトル

Last updated at Posted at 2021-04-17

今日はLiveViewHTML titleをページ移動の際に更新する方法についてまとめます。

Phoenix LiveView 公式ドキュメントによると、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

  ...

これで問題は解決しましたが、もうちょっと踏み込んで「モジュール名をもとにページタイトルを生成できないのか」興味が湧いてきました。

Phoenix.Namingという便利なモジュールがありました。

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

Phoenix.Namingを用いて簡単な関数を書きました。

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

  ## Examples

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

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

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

そしてLiveViewのmountassignします。

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

  ...

手作業で各ページのタイトルを決定してもたいして時間がかからないので、いちいちこんなことする必要はないのかもしれませんが、ここに至るまでの学びのプロセスを楽しみました。

あえてメリットいうと、新しいLiveViewを作成する際にコピー・ペーストでできることでしょうか。

個人的にはこのシンプルなソリューションに満足していますが、マクロ等を駆使したもっときれいなアプローチがあるのかもしれません。

そういえば、サイト全体のタイトルを自分の好みに設定するために、以前にこういうのを書きました。

国際化 (i18n)にも挑戦したいですね。

以上

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0