开发者

Render specific method outside the application.html.erb template

I am trying to make some kind of personal pages for users on my webap开发者_如何学Cp. Thus I want to use different CSS templates and layouts than the rest of my pages.

For example I have all my layout in application.html.erb in which all content is rendered within the 'yield' call.

Now I want a specific method of a controller (for example show_personal_page in UsersController) to redirect to a totally different layout and style (perhaps even customizable for every user). The problem is that anything I do will pass though the application.html.erb template and thus will look the same.

I thought of one way to do this is to put 'if' and 'else' clauses inside application.html.erb but that just doesn't seem to be right (i.e. not rails style at all)

Any ideas?

Thanks!


You can always define custom layout for your controller by defining it at the top:

class UsersController
  layout 'user'
  .
  .
end

Infact if you create layout with name users.html.erb in app/views/layout, Rails will automatically use that layout for every view in the users_controller(i.e. if you make a layout with your controller's name).

If you want to use the layout for a specific method in the controller, you can use

class UsersController
  layout 'user', :only => :show_personal_page
  .
  .
end

or you can directly call the layout in the method

class UsersController
  def show_personal_page
    .
    render :layout => :user
  end
end

You can choose not to use any layout by using render :layout => false in the method, or using layout nil at the top of the controller.

If you want to specify layout conditionally, the best way to do it will be like this

class UsersController
  layout :conditional_layout, :only => :show_personal_page

  def conditional_layout
    ..(your condition)
    (return correct layout)
  end
  .
  .
end


You can render specific layouts from your users controller:

class UsersController < ApplicationController
  ...

  def controller_method
    #should be a string (:layout requires a string)
    var user_specific_layout = get_specific_layout(user)
    render :layout  => user_specific_layout
  end
end

Check out the Layouts and Rendering in Rails guide for more info.


Create a new layout in views/layouts/user.html.erb, then set it in the controller with:

layout 'user'

Or you could set layout false and put all the structure of the page in the view file, and not depend on a layout at all.


You can also pass a proc to the layout method:

def MySuperController < ApplicationController
  layout Proc.new{|controller| controller.current_user.layout}
  ...
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜