Yes. ViewComponent is tested against ERB, Haml, and Slim, but it should support most Rails template handlers.
If the view could benefit from unit testing, making it a ViewComponent is probably a good idea.
When rendering multiple times the same component, you may want to render it only once, from the controller action, and reuse it.
class PagesController < ApplicationController def index # Does not work: triggers a `AbstractController::DoubleRenderError` # @reusable_icon = render IconComponent.new('close') # Does not work: renders the whole index view as a string # @reusable_icon = render_to_string IconComponent.new('close') # Works: renders the component as a string @reusable_icon = IconComponent.new('close').render_in(view_context) end
ViewComponent is far from a novel idea! Popular implementations of view components in Ruby include, but are not limited to:
ViewComponent does not include support for validations. However, it can be added by using
class ExampleComponent < ViewComponent::Base include ActiveModel::Validations # Requires that a content block be passed to the component validate :content, presence: true def before_render validate! end end
Note: Using validations in this manner can lead to runtime exceptions. Use them wisely.
ViewComponent is currently only available for Rails. Read more: compatibility section.