Best practices for adding HTML helpers within LiveView template?

I’m refactoring an existing Phoenix template with partials to a some.html.leex template to be in the same directory as the LiveView, some.ex. After inling the partials into the some.html.leex template the LiveView cannot locate any of the default form helpers and view functions. For example, I’m seeing the error message:

warning: undefined function error_tag/2
warning: undefined function text_input/3

Thus, what’s the best practice for adding and using standard HTML tag functions within a LiveView?

1 Like

You define these imports in lib/my_app_web.ex:

defp view_helpers do
  quote do
    # Use all HTML functionality (forms, tags, etc)
    use Phoenix.HTML

    # Import LiveView helpers (live_render, live_component, live_patch, etc)
    import Phoenix.LiveView.Helpers

    # Import basic rendering functionality (render, render_layout, etc)
    import Phoenix.View

    import MyAppWeb.ErrorHelpers
    import MyAppWeb.Gettext
    alias MyAppWeb.Router.Helpers, as: Routes
  end
end

error_tag/2 comes from import MyAppWeb.ErrorHelpers, while text_input/3 comes from use Phoenix.HTML.

Then, view_helpers/0 is referenced in the same file:

def live_view do
  quote do
    use Phoenix.LiveView,
      layout: {MyAppWeb.LayoutView, "live.html"}

    unquote(view_helpers())
  end
end

which then imports the helpers into your LiveViews due to the inclusion of use MyAppWeb, :live_view

5 Likes