Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

rails 3, how add a view that does not use same layout as rest of app?

I could not find any docs or examples on how to structure my app to allow different views in the same controller to use completely different layouts and stylesheets.

Our app was scaffolded and we then used nifty-generators to generate views, then added devise for authentication. We have views and controllers for two models: widgets and companies.

I currently have a single layout: layouts/application.html.haml, I don't see that referenced anywhere so I assume (a rails newbie) that it's always used by naming convention.

I now need to add a couple of views (for mobile browsers) which have a different stylesheet and layout (for example, no login/logout links in the top right), within the same controllers.

How can that be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

By default, layouts/application.html.haml (.erb if you are not using haml).

In fact, layout file could be set per controller or per action, instead of per view, per view folder.

There are few cases:

To change the default layout file for all controller (ie. use another.html.haml instead of application.html.haml)

class ApplicationController < ActionController::Base
  layout "another"

  # another way
  layout :another_by_method
  private
  def another_by_method
    if current_user.nil?
      "normal_layout"
    else
      "member_layout"
    end
  end
end

To change all actions in a certain controller to use another layout file

class SessionsController < ActionController::Base
  layout "sessions_layout"
  # similar to the case in application controller, you could assign a method instead
end

To change an action to use other layout file

def my_action
  if current_user.nil?
    render :layout => "normal_layout"
  else
    render :action => "could_like_this", :layout => "member_layout"
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...