Odd behavior when rendering components within a partial #380
-
So I think this is likely a gap in my understanding somewhere rather than an issue so any help understanding what is going on would be appreciated. Take the following
When rendering within a partial, it works as expected if I call the
However, when trying to render the component directly in the partial the row content remains empty:
It occurs to me that this could just be a side effect of mixing partials and components, which is how I'm handling the overall refactor. If this is expected and clarity would be appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
ERB works based on the return values of method calls. When you see def =(output)
if output.is_a?(String)
@output_buffer << output
end
end In your first example, you are telling ERB to output the return value of the row rendered by ActionView (line 2). <%= render Views::Row.new(**opts) do |row| While that is being calculated, you tell the row to render the cells (line 4). row.render_cell(cell, **cell_opts) This isn’t ActionView’s In the end, the output returned to In the second example, you tell ActionView to output the row (line 2). <%= render Views::Row.new(**opts) do |row| And before the row has a return value, you tell ActionView to render the cells but don’t tell ERB to output the result (line 4). render Views::Cell.new(cell: cell, **opts) This is in ERB land, so Here's a third example which is how I’d recommend using Phlex in ERB: <%= render Views::Row.new(**opts) do |row| %>
<% cells.each do |cell| %>
<%= render Views::Cell.new(cell: cell, **opts) %>
<% end %>
<% end %> Here we tell ERB to output the row (line 1) then we tell ERB to output the cell (line 3). Because we close the ERB tags on each line, we can easily interlace additional HTML if we want to. <%= render Views::Row.new(**opts) do |row| %>
<div class="around_the_row">
<h1>Inside the row</h1>
<% cells.each do |cell| %>
<h2>Inside the cell</h2>
<%= render Views::Cell.new(cell: cell, **opts) %>
<% end %>
</div>
<% end %> |
Beta Was this translation helpful? Give feedback.
-
That helps, thanks! |
Beta Was this translation helpful? Give feedback.
ERB works based on the return values of method calls. When you see
<%=
, you can think of the=
as being a method that pushes things to the output buffer. In pseudo code, it’s something like this.In your first example, you are telling ERB to output the return value of the row rendered by ActionView (line 2).
While that is being calculated, you tell the row to render the cells (line 4).
This isn’t ActionView’s
render
method, it’s the Phlexrender
method and in Phlex,render
immediately outputs. You don’t need to say= render
.In the en…