目标:
掌握 Controller中: render :layout的用法
步骤:
Step 01: 基础用法
Rails预设的布局是app/view/layouts/application.html.erb这个文件。
但是有时我们会希望不同页面采用不同的布局,比如后台(admin)和前台(user)使用不同的页面。
这时候我们就可以建立一个新的布局app/view/layouts/admin.html.erb
只要在Controller中指定使用admin布局即可:
1 2 3
| class AdminsController < ApplicationController layout "admin" end
|
Step 02: 稍微进阶一点的做法:
我们也可以指定某个action要使用admin布局:
1 2 3 4 5 6 7 8 9 10 11 12 13
| class AdminsController < ApplicationController layout "admin", :only => :new def show render :layout => "admin" end def index render :template => "others/weired_topics", layout: "admin" end end
|
Step 03: 其他技巧
此外为了减少代码的重复,如果后台涉及的controller很多,可以专门在BaseController做完后台所以Controller的父controller,然后仅在BaseController中指定使用admin布局即可。比如:
参考代码:https://github.com/Kerzzi/jfshop/tree/master/app/controllers/admin
app/controllers/admin/base_controller.rb1 2 3 4 5 6 7 8
| class Admin::BaseController < ActionController::Base layout 'layouts/admin' before_action :authenticate_user! before_action :admin_required end
|
其他Controller的父controller 都是Admin::BaseController
app/controllers/admin/categories_controller.rb1 2 3
| class Admin::CategoriesController < Admin::BaseController end
|
app/controllers/admin/orders_controller.rb1 2 3
| class Admin::OrdersController < Admin::BaseController end
|
app/controllers/admin/product_images_controller.rb1 2 3
| class Admin::ProductImagesController < Admin::BaseController end
|
app/controllers/admin/product_images_controller.rb1 2 3
| class Admin::ProductsController < Admin::BaseController end
|
更多ROR【豆知识】:
更多ROR【豆知识】请前往:https://github.com/Kerzzi/ruby_notes/tree/master/04_ROR_beans