Setting up a nested slot #1647
-
Thanks to @neanias for prompting this. You may have three layers of depth you'd like to travel through with components. Say you have a You can do so by defining a method # frozen_string_literal: true
class ParentComponent < ViewComponent::Base
renders_one :child, ChildComponent
def with_grandchild(*args, &block)
with_child { |child| child.with_grandchild(*args, &block) }
end
end Now, instead of needing to traverse through all three layers... <%= render ParentComponent do |p| %>
<% p.child do |c| %>
<% c.grandchild %>
<% end %>
<% end %> You can instead... <%= render ParentComponent do |p| %>
<% p.with_grandchild %>
<% end %>
EDIT: You can pass a block through too. I've updated the method signature to show that. <%= render ParentComponent.new do |p| %>
<% p.with_grandchild do %>
<%= tag.div(style: "border: 1px solid gray") { "And it takes a block!" } %>
<% end %>
<% end %> |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
@boardfish clever! Almost feels like a |
Beta Was this translation helpful? Give feedback.
-
Updated syntax to leverage Ruby 2.7+ argument forwarding with # frozen_string_literal: true
class ParentComponent < ViewComponent::Base
renders_one :child, ChildComponent
def with_grandchild(...)
with_child { |child| child.with_grandchild(...) }
end
end |
Beta Was this translation helpful? Give feedback.
Updated syntax to leverage Ruby 2.7+ argument forwarding with
...
: