Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Was implementing an analogue of render_many for a live_component. Should have worked like this:

<%= exhibit(@collection, SomeComponent, socket: @socket, as: :some) %>
  require Phoenix.LiveView.Helpers
  alias Phoenix.LiveView.Helpers, as: View

  def exhibit(collection, component, params \ [], socket: socket, as: item_name) when is_list(collection) do
    Enum.map(collection, fn item ->
      View.live_component socket, component, some: item
    end)
  end

Well, it seems like this is not possible:

A component must always be returned directly as part of a LiveView template.

For example, this is not allowed:

<%= content_tag :div do %>
  <%= live_component @socket, SomeComponent %>
<% end %>

That's because the component is inside content_tag. However, this works:

<div>
  <%= live_component @socket, SomeComponent %>
</div>

Components are also allowed inside Elixir's special forms, such as if, for, case, and friends.

<%= for item <- items do %>
  <%= live_component @socket, SomeComponent, id: item %>
<% end %>

However, using other module functions such as Enum, will not work:

<%= Enum.map(items, fn item -> %>
  <%= live_component @socket, SomeComponent, id: item %>
<% end %>

Tried few other things to make it work, but it seems hopeless. Any clue how to implement render_many for a live_component or I have to live with those ugly for loops in templates?

question from:https://stackoverflow.com/questions/65852820/render-live-component-outside-a-template

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
698 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...