Slot Predicates for slot content
dlinch opened this issue · comments
Feature request
It would be helpful if in addition to the provided slot predicates that help me determine if a slot was called, there was one that was providing the actual content was valid/present.
Motivation
We ran into this scenario recently:
The template for a different component has to add a line or boolean logic to present a slot:
<%= render CardComponent do |card| %>
<% card.with_title { title } %>
<% if description.present? %>
<% component.with_description { 'So Descript, Much Wow' } %>
<% end %>
<% end %>
Card component renders the description using a Description Component, so this isn't just content displayed in the card components template.
I was investigating whether I could remove some of these guard clauses from the templates by using the render?
method. It seemed like it should be up to the individual component whether it renders itself based on the passed in data being "valid" or not.
Given an example ViewComponent:
class DescriptionComponent < ApplicationComponent
renders_one :description, ->(**opts, &block) do
# .. etc
end
def initialize()
# ... etc
end
def render?
description?
end
end
The description?
method is always true, because it checks whether the slot was invoked or not, which makes sense given the template logic above and if I were to remove the if
preventing the conditionally calling. If I try and access description directly:
def render?
description
end
This would work normally give a vanilla slot, a la renders_one :description
, but given its a lambda that we use to add some class/stylings/sugar on top of, it will always return me an HTML tag with no content in it.
Thus, it seemed like having access to the raw slot value for me to pass some kind of validation upon in render?
would be beneficial. Then the component can determine whether it should render or not, and my unrelated component above doesn't need to conditionally render the description slot.
@dlinch thanks for taking the time to file this issue! It's good to see you around ❤ What if we added a SLOTNAME_present?
method? Would you be up for writing a PR?
@joelhawksley I could give it a shot! I'll try and get something out in the next couple of days.