You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I tired to figure out how to render a ViewComponent or not according to its content 🤔
My use case is:
classDefinitionEntryComponent < ViewComponent::Basedefinitialize(term:,description: nil)@term=term@description=descriptionenddefcall# do somethingendprivateattr_reader:termdefdescription@description || contentendendend
Here, my description is either the one given at initialisation, or the block content of my component.
What I want to achieve is to render my component only if the actual description is not null. My first approach was to implement the #render? method like this:
defrender?
!description.nil?end
This sounds great. But the #render? method arrives too early in the ViewComponent lifecycle, and content has not been evaluated by the time the method is called 😢
Workaround
What I discovered by digging into the ViewComponent::Base class and the documentation is that the #render? method is actually called twice in the lifecycle. Here's a workaround that takes advantage of this:
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I tired to figure out how to render a ViewComponent or not according to its content 🤔
My use case is:
Here, my description is either the one given at initialisation, or the block content of my component.
What I want to achieve is to render my component only if the actual description is not null. My first approach was to implement the
#render?
method like this:This sounds great. But the
#render?
method arrives too early in the ViewComponent lifecycle, andcontent
has not been evaluated by the time the method is called 😢Workaround
What I discovered by digging into the
ViewComponent::Base
class and the documentation is that the#render?
method is actually called twice in the lifecycle. Here's a workaround that takes advantage of this:I'd be happy to use the
#content_evaluated?
method, but I only need the first part of the conditional.view_component/lib/view_component/base.rb
Lines 326 to 328 in cdd934c
Question
Do you know a better way of achieving my goal without using the instance variables of the
ViewComponent::Base
class?Beta Was this translation helpful? Give feedback.
All reactions