views:

177

answers:

3

(Rails version 2.3.2)

By default the :layout parameter for render takes a relative path and adds this to the default layout directory ("app/views/layout").

Eg:

render :file => '../resources/website/home_page.html.erb', :layout => '../../../../resources/website/layout'

"If no directory is specified for the template name, the template will by default be looked for in app/views/layouts/. Otherwise, it will be looked up relative to the template root."

-http://api.rubyonrails.org/classes/ActionController/Layout/ClassMethods.html

However, the above only works in development mode, and breaks in production, failing to find the template. Exception: ActionView::MissingTemplate

Either way, I would rather specify the direct path to a layout file.

(The idea is to keep the specified layout file separate from the main project views, in a plugin-like way.)

Is this possible?

I could temporarily (instance only) override the method "default_layout" in ActionController::Layout? (But im not sure how?)

Thanks for reading.

A: 

Probably the only good way to do this would be to make a constant in your environment.rb with the path for whatever box you're on. So something like

LAYOUT_PATH = '/var/www/templates'

The other option would be to keep the templates in the correct directory but use an svn external or the equivalent in your SCM of choice to keep that template directory up to date with all the other sites that use the same templates.

Chuck Vose
Thanks, but unfortunately I need to override LAYOUT_PATH per request, with different directory paths.
Reilly
A: 

If you need to resolve layout per request, try:

class ApplicationController < ActionController::Base
  layout :resolve_layout

  # some definitions

protected

  def resolve_layout
    # some logic depending on current request
    path_to_layout = RAILS_ROOT + "/path/to/layout"
    return path_to_layout
  end

end

I hope, that is what you need.

Konstantin
A: 

You can probably add to the controller view paths (see here) to allow your app to pick up templates from different directories. This could potentially also cure your other weird template paths.

If you want absolute paths, use RAILS_ROOT, as suggested here. If you want to share views from a plugin, you may also want to check out the rails-engines plugin.

But also remember that Rails (kind of intentionally) makes doing strange things hard. If you don't have a really strong reason to do otherwise, you'll enjoy a smoother ride by sticking to the defaults.

averell