Page title via live view route that’s compatible with existing code in regular views?



Here’s the code I use to set the page title in my Layout template:

<title><%= @view_module.title(action_name(@conn), assigns) %></title>

Here’s a sample of what I have in one of my Views:

defmodule ZoinksWeb.TaskView do
  use ZoinksWeb, :view
  alias ZoinksWeb.TaskLive

  def title(_action, _assigns), do: "Tasks"

However, now that I’m trying to implement Live View - @view_module ends up being “Phoenix.LiveView.Controller” (rather than a user-defined view).

Is there something I can do with Live View that will work with regular Views that’s similar to my existing solution? Or should I just regress to setting an assign in the controller and/or live view?



I don’t think you can do this right now with LiveView. But I do know that browser pushState support is on the roadmap, so I would not be too surprised if updating the page title would also be part of this.



I think I’ve figured out a way to do it. Looks like there’s a @live_view_module assign. Here’s what my title tag looks like now:

<title><%= title(@conn, assigns) %></title>

In LayoutView, this is what the title function looks like:

def title(conn, assigns) do
  try do
    cond do
      assigns |> Map.has_key?(:live_view_module) ->
        module = assigns[:live_view_module]

      assigns |> Map.has_key?(:view_module) ->
        module = assigns[:view_module]
        action = action_name( conn )

        module.title( action )
    x -> “Default Title"

I put the try/catch in there because I don’t know if there’s a way to check if a function exists for a module?

1 Like

iex(1)> h function_exported?

                def function_exported?(module, function, arity)                 

  @spec function_exported?(module(), atom(), arity()) :: boolean()

Returns true if module is loaded and contains a public function with the given
arity, otherwise false.

Note that this function does not load the module in case it is not loaded.
Check Code.ensure_loaded/1 for more information.

Inlined by the compiler.

## Examples

    iex> function_exported?(Enum, :member?, 2)


1 Like


Sweet, thanks!

1 Like