How to call a named template #2068
-
I'm new to view components. What I'm trying to achieve is this
Is there anyway to call the template name directly from list_component.rb? Something like
Or do I need to do all this inside of a `list_component.html.erb'? e.g.
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hey @bufordtaylor, thanks for opening this! I think what this code is pointing towards is that this markup is different enough to warrant new components for each case. Rather than having the template or component class contain lots of conditionals to switch behaviour, you'll most likely want to break these out into separate components. If you wanted # Intentionally doesn't inherit from ViewComponent::Base: this is a plain old Ruby factory class.
class ListComponent
def self.new(preference)
case preference
in :compact_row
CompactRowComponent.new
in :standard_row
StandardRowComponent.new
in :compact_card
CompactCardComponent.new
in :standard_card
StandardCardComponent.new
end
end
end Then you could: <%= render ListComponent.new(:compact_row) %> and it'd work, but I'd probably just render them directly anyway: <%= render CompactRowComponent.new %> Based on the names you've given these classes, I'd also encourage you to have a look at slots, particularly polymorphic slots, which you could use to specify whether you want to render a compact or standard component in a certain context. Hope this helps! |
Beta Was this translation helpful? Give feedback.
Hey @bufordtaylor, thanks for opening this! I think what this code is pointing towards is that this markup is different enough to warrant new components for each case. Rather than having the template or component class contain lots of conditionals to switch behaviour, you'll most likely want to break these out into separate components.
If you wanted
ListComponent
to be the interface folks use to render this component, though, you could make that a factory class: