Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

phoenix framework - Render live_component outside a template

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

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...