By default, Rails can find views with the format, locale and template language in the filename (so I can create index.de.json.erb)
Is it possible to add another, custom parameter to the view’s filename?
I would like to pass the current subdomain, so http://foo.example.com/ would render index.foo.html.erb, and http://bar.example.com/ would render index.bar.html.erb (both of them with index.html.erb fallback).
The resolving pattern that is used to look up views can only contain variables that are registered with the
ActionView::LookupContextclass. The first step is therefore to register a new variable (subdomain) with theLookupContextclass. You should do this in an initializer:Now the
LookupContextknows about thesubdomain, it can be included in the resolving pattern. For more detail about changing the resolving pattern, see theActionView::FileSystemResolverdocumentation, but essentially you should include the following, also in an initializer:This pattern is eventually passed to
Dir.glob(after the:*variables have been replaced). The glob pattern{.:subdomain,}means “either.:subdomainor nothing”, which provides the fallback to a view file with no subdomain if the file with a subdomain isn’t found.The final step is to update your
ApplicationControllerto pass the subdomain to theLookupContext:(This answer was mostly figured out by reading source code, some of these features aren’t documented. It was tested with Rails 3.2.5)