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

For anyone looking how to add page titles to both LiveViews and regular views, here is a code example using @OvermindDL1’s suggestion:

Include this in your html header:

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

Next, include the following in your layout_view.ex file:

def title(conn, assigns) do
  cond do
    function_exported?(assigns[:live_view_module], :title, 1) ->
      apply(assigns[:live_view_module], :title, [assigns])

    function_exported?(assigns[:view_module], :title, 2) ->
      action = action_name(conn)
      apply(assigns[:view_module], :title, [action, assigns])
      
    true -> "Default title"
  end
end

You can then use a title/1 function in your LiveView and a title/2 function in your regular views.

4 Likes