Rendering template dynamically in Rails ViewComponent

315 views Asked by At

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...

1

There are 1 answers

0
Maxence On

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:

def content
  renderer = ERB.new(@file_content)
  renderer.result(binding)
end

file path being declared in the initialize method this way :

file_path = "app/components/section_component/#{section_name}.html.erb"
@file_content = File.read(file_path)

And my viewComponent view is made of a single line of code :

<%= content.html_safe %>

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..