每个动作的轨道布局?

我对一些操作使用不同的布局(主要是对大多数控制器中的新操作)。

我想知道指定布局的最佳方式是什么?(我在同一个控制器中使用3个或更多不同的布局)

我不喜欢吸毒

Render: layout = > ‘ name’

我喜欢这么做

布局‘ name’,: only = > [ : new ]

但是我不能用它来指定2个或更多不同的布局。

例如:

当我在同一个控制器中调用布局2次,使用不同的布局名称和不同的唯一选项时,第一次会被忽略——这些操作不会在我指定的布局中显示。

注意: 我正在使用 Rails 2。

78982 次浏览

可以使用方法设置布局。

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

您可以使用 回应为单个操作指定布局:

  def foo
@model = Bar.first
respond_to do |format|
format.html {render :layout => 'application'}
end
end

这里有一个 gem (layby _ action) :)

layout_by_action [:new, :create] => "some_layout", :index => "other_layout"

Https://github.com/barelyknown/layout_by_action

如果只在两种布局之间进行选择,可以使用 :only:

class ProductsController < ApplicationController
layout "admin", only: [:new, :edit]
end

或者

class ProductsController < ApplicationController
layout "application", only: [:index]
end

您还可以使用呈现指定操作的布局:

def foo
render layout: "application"
end

指定控制器下布局的各种方法:

  1. 在以下代码中,将在索引下调用 application _ 1布局,并显示用户控制器的操作,其他操作将调用应用程序布局(默认布局)。

    class UsersController < ApplicationController
    layout "application_1", only: [:index, :show]
    end
    
  2. In following code, application_1 layout is called for all action of Users controller.

    class UsersController < ApplicationController
    layout "application_1"
    end
    
  3. In following code, application_1 layout is called for test action of Users controllers only and for all other action application layout(default) is called.

        class UsersController < ApplicationController
    def test
    render layout: "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,如果 params print 出现的话。