Skip to content

Commit e9d9920

Browse files
authored
Merge pull request #2510 from ViewComponent/2484-fixed
See 2484
2 parents 1054cf6 + c67892c commit e9d9920

File tree

5 files changed

+21
-1
lines changed

5 files changed

+21
-1
lines changed

docs/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ nav_order: 6
1010

1111
## main
1212

13+
* Capture partial block in the component's context, allowing access to the component instance inside the block.
14+
15+
*23tux*
16+
1317
* Add `after_compile` class method hook to enable extensions to run logic after component compilation.
1418

1519
*Jose Solás*

lib/view_component/base.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,14 +260,17 @@ def render(options = {}, args = {}, &block)
260260
@view_context.render(options, args, &block)
261261
elsif block
262262
__vc_original_view_context.render(options, args) do
263+
# capture the block output in the view context of the component
264+
output = capture(&block)
265+
263266
# Partials are rendered to their own buffer and do not append to the
264267
# original @output_buffer we retain a reference to in #render_in. This
265268
# is a problem since the block passed to us here in the #render method
266269
# is evaluated within the context of ViewComponent::Base, and thus
267270
# appends to the original @output_buffer. To avoid this, we evaluate the
268271
# block in the view context instead, which will append to the output buffer
269272
# created for the partial.
270-
__vc_original_view_context.instance_exec(&block)
273+
__vc_original_view_context.capture { output }
271274
end
272275
else
273276
__vc_original_view_context.render(options, args)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<%= render "shared/yielding_partial" do %>
2+
<%= world %>
3+
<% end %>
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class PartialWithYieldAndMethodCallComponent < ViewComponent::Base
2+
def world
3+
"world"
4+
end
5+
end

test/sandbox/test/rendering_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1339,4 +1339,9 @@ def test_render_partial_with_yield
13391339
render_inline(PartialWithYieldComponent.new)
13401340
assert_text "hello world", exact: true, normalize_ws: true
13411341
end
1342+
1343+
def test_render_partial_with_yield_and_method_call
1344+
render_inline(PartialWithYieldAndMethodCallComponent.new)
1345+
assert_text "hello world", exact: true, normalize_ws: true
1346+
end
13421347
end

0 commit comments

Comments
 (0)