Why doesn't Phoenix has a def component in *_web.ex?

In my Phoenix Liveview project, I wanted to use a functional component and inside that markup call a function from core_components.

I had to create a new function in *_web.ex in order to do this - otherwise I couldn’t call the functions in core_components.ex:

defmodule TestWeb.DashboardSidebarComponent do
  use TestWeb, :component

  def sidebar(assigns) do
    # markup
  end
end

And in *_web.ex I had to add this function called component.

  def component do
    quote do
      use Phoenix.Component

      unquote(html_helpers())
    end
  end

Shouldn’t Phoenix do this automatically for me? If so I’ll open an issue in the Phoenix repo.

For functional components, there’s use TestWeb, :html which includes what your component/0 does as well as imports some functions from Phoenix.Controller.

  def html do
    quote do
      use Phoenix.Component

      # Import convenience functions from controllers
      import Phoenix.Controller,
        only: [get_csrf_token: 0, view_module: 1, view_template: 1]

      # Include general helpers for rendering HTML
      unquote(html_helpers())
    end
  end

Here’s an example:

3 Likes

Didn’t notice that function directly below lol - thank you!

1 Like