How to render a ViewComponent conditionally depending on its content? #2215
-
I tired to figure out how to render a ViewComponent or not according to its content 🤔 My use case is: class DefinitionEntryComponent < ViewComponent::Base
def initialize(term:, description: nil)
@term = term
@description = description
end
def call
# do something
end
private
attr_reader :term
def description
@description || content
end
end
end 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 def render?
!description.nil?
end This sounds great. But the WorkaroundWhat I discovered by digging into the def render?
return true unless defined?(@__vc_content_evaluated)
!description.nil?
end I'd be happy to use the view_component/lib/view_component/base.rb Lines 326 to 328 in cdd934c QuestionDo you know a better way of achieving my goal without using the instance variables of the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I was unable to validate this issue, even by copying your provided component into the test suite: #2343. I'm going to close this as outdated but please reopen as an issue if this is still a problem for you ❤️ |
Beta Was this translation helpful? Give feedback.
I was unable to validate this issue, even by copying your provided component into the test suite: #2343. I'm going to close this as outdated but please reopen as an issue if this is still a problem for you ❤️