Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I intercept rails's template rendering

I have an application which serves more than one website. Similar to Stack Exchange, these several sites behave very similarly to each other.

Given the following views directory structure:

views/
  shared/users/index.html.erb
  app1/users/index.html.erb
  app2/users/

How can I re-write the default template rendering in Rails so that

  • when App1's UsersController#index is called, it renders app1/users/index.html.erb
  • when App2's UsersController#index is called, it realises there is no index.html.erb template so for checks shared/users/index.html.erb before raising the missing template error

Thanks in advance

like image 720
bodacious Avatar asked Dec 28 '22 20:12

bodacious


2 Answers

I know you already accepted an answer for this, but I don't think you need to create your own template resolver.

If I understand your question correctly, you are trying to "theme" your views depending on some aspect of the current state of the app. I have done the same thing previously using this dandy little controller method:

prepend_view_path "app/views/#{current_app_code}"

Throw this in a before_filter in your application controller, and all your controllers will obey:

class ApplicationController < ActionController::Base
  before_filter :prepend_view_paths

  def prepend_view_paths
    prepend_view_path "app/views/#{current_app_code}"
  end

end

Now rails will first look for "app/views/app1/users/index.html.erb" when "/users" is requested if "app1" is the current app.

If it doesn't find it there, it rolls back to the default location at "app/views/users/index.html.erb".

Hope this gives you another alternative.

like image 145
twmills Avatar answered Jan 10 '23 19:01

twmills


I believe that you'll have to code your own Template Resolver. Perhaps this blog post can help.

like image 45
Roman Avatar answered Jan 10 '23 20:01

Roman