I have a SectionComponent Class as follow :
class SectionComponent < ViewComponent::Base
def initialize(..)
...
end
end
And a matching section_component.html.erb
file.
It works perfectly fine.
Though I want to render a different template depending on a keyworded argument in the intialize method. And I can't figure out how to render a different template.
I have tried to explicitly render a different template (without playing with the intialize method yet):
def render
render_template(:section_details_component, template_path: "section_details_component.html.erb")
end
But each time my server complains it can't find the template. Actually the render block seems to never be hit. Is there a specific syntax to adding a different template ? Or maybe a workaround ?
Otherwise I will write as many components as I have templates...
Seems like ViewCompoennt is not designed to handle different templates for the same component.
My solution is to have a content method that loads an .erb file dynamically:
file path being declared in the
initialize
method this way :And my viewComponent view is made of a single line of code :
This is obviously a edge case for a viewcompoennt. I have used a compoennt here instead of using a partial in order to separate logic, and because I have several degrees of nested partials for which locals forwarding is not trivial. ViewCompoennt solves these issues..