我对某些操作使用不同的布局(主要用于大多数控制器中的新操作)。
我想知道指定布局的最佳方法是什么? (我在同一个控制器中使用 3 个或更多不同的布局)
我不喜欢使用
渲染:布局 => '名称'
我喜欢做
布局'名称', :only => [:new]
但我不能用它来指定 2 个或更多不同的布局。
例如:
当我在同一个控制器中使用不同的布局名称和不同的唯一选项调用布局 2 次时,第一个被忽略 - 这些操作不会显示在我指定的布局中。
注意:我使用的是 Rails 2。
您可以使用一种方法来设置布局。
class MyController < ApplicationController
layout :resolve_layout
# ...
private
def resolve_layout
case action_name
when "new", "create"
"some_layout"
when "index"
"other_layout"
else
"application"
end
end
end
如果您只在两种布局之间进行选择,您可以使用 :only
:
class ProductsController < ApplicationController
layout "admin", only: [:new, :edit]
end
或者
class ProductsController < ApplicationController
layout "application", only: [:index]
end
(I am using 3 or more different layouts in the same controller)
。这个答案允许布局和没有布局,not 不同的布局。
您可以使用 respond_to 指定单个操作的布局:
def foo
@model = Bar.first
respond_to do |format|
format.html {render :layout => 'application'}
end
end
layout "[...]" to the controller class only allows one statement effectively. If you have more than two layouts to deal with (say, admin, generic_app, tailored_app), you will experience
在此操作中多次调用渲染和/或重定向来干燥事物` 错误;你别无选择,只能使用这个建议。
format.html { render 'custom_index', layout: 'application' }
。
您还可以使用渲染指定操作的布局:
def foo
render layout: "application"
end
有一个 gem (layout_by_action) :)
layout_by_action [:new, :create] => "some_layout", :index => "other_layout"
https://github.com/barelyknown/layout_by_action
在控制器下指定布局的各种方法:
在下面的代码中,application_1 布局在用户控制器的 index 和 show 操作下调用,其他操作调用应用程序布局(默认布局)。 class UsersController < ApplicationController layout "application_1", only: [:index, :show] end 在下面的代码中,users 控制器的所有动作都会调用 application_1 布局。 class UsersController < ApplicationController layout "application_1" end 在下面的代码中,application_1 布局仅用于用户控制器的测试操作,而所有其他操作应用程序布局(默认)被调用。 class UsersController < ApplicationController def 测试渲染布局:“application_1” end end
精确 :
您在上面看到的不是真正但有效的 DRY 方式,但具有精确性:布局需要在您的变量之后才能工作(“@some”)。作为 :
def your_action
@some = foo
render layout: "your_layout"
end
并不是 :
def your_action
render layout: "your_layout"
@some = foo
@foo = some
end
如果你做一个 before_action... 它也行不通。
希望能帮助到你。
你可以像我的例子一样使用它:
def show
...
render layout: "empty",template: "admin/orders/print" if params.key?('print')
end
如果参数打印存在,我指定了布局和模板 html.erb。
不定期副业成功案例分享
layout Proc.new{ ['index', 'new', 'create'].include?(action_name) ? 'some_layout' : 'other_layout' }