Rendering view component template variants outside of the current request.

Published on February 22, 2024
Written by Daniel Schoppmann

Rails variants are a technique to allow rendering of different template or partial variants, for example, to render different web and ios/android views, even though the underlying controller logic is the same. If you'd have a partial _new.html.erb, you'd could also provide a partial _new.html+ios.erb which would automatically being called if the request object is set to this preferred variant.

As heavy users of GitHub's view_component gem, we are happy that the gem supports variants natively as well. However, sometimes we run into a situation where we want to access a variant of the component without relying on the current request variant. It turns out that calling the component with the usual render MyComponent.new, variant: 'custom_variant' does not work. It's tight to the current view context of the given controller.

Luckily there is the Rails ActionController::Rendering class, which is exactly made for this: To render arbitrary templates without being inside a controller action.

So, for example, if you are in a place in your Rails view and you need to explicitly address a variant template that is outside the current view_context variant, you can do so with:

<%= ApplicationController.render(MyComponent.new, variant: 'custom_variant') %>
Subscribe to get future articles via the RSS feed .