【问题标题】:Template inheritance in 3.1 for controllers in namespace3.1 中命名空间中控制器的模板继承
【发布时间】:2011-07-18 08:46:16
【问题描述】:

我像往常一样在视图/布局中有一个 application.html.erb,其中 用于内容。现在我正在为用户帐户编写一个设置页面,其中包含许多不同的页面(个人资料、帐户、通知等)。

控制器/settings_controller.rb

class SettingsController < ApplicationController
end

controllers/settings/account_settings_controller.rb

class Settings::AccountSettingsController < ApplicationController
end

控制器/设置/profile_settings_controller.rb

class Settings::ProfileSettingsController < ApplicationController
end

对于属于 Settings 命名空间的每个控制器,我希望“始终呈现视图”,特别是包含的 views/settings/master.html.erb

<markup>
  <%= yield(:settings_content) %>
</markup>

例如,视图 settings/profile_settings/edit.html.erb 将包含

<% content_for(:settings_content) do %>
  <markup>
  </markup>
<% end %>

我不知道从哪里开始。也许我的控制器应该看起来像

class Settings::AccountSettingsController < SettingsController
end

欢迎任何指导。

编辑:

Rendered settings/account_settings/edit.html.erb within layouts/application (19.6ms)

应该变成

Rendered settings/master.html.erb within layouts/application (19.6ms) 
Rendered settings/account_settings/edit.html.erb within settings/master (19.6ms)

【问题讨论】:

    标签: ruby-on-rails templates ruby-on-rails-3.1 template-inheritance


    【解决方案1】:

    在settings_controller中写layout 'settings/master,你需要从这个继承命名空间控制器

    【讨论】:

    • 这就是我现在使用的那种。问题是我希望 settings/master '继承'布局/应用程序,以便 吐出 settings/master 的内容。我目前正在使用一个非常糟糕的解决方案,所以我没有回答我自己的问题,而是在等待其他方法来解决这个问题。
    【解决方案2】:

    我建议使用它来拥有一个使用 haml 嵌套子布局的主布局:

    将此方法添加到您的 application_helper.rb

      # Allows easy using nested layouts
      def inside_layout(layout = 'application', &block)
        render :inline => capture_haml(&block), :layout => "layouts/#{layout}"
      end
    

    布局/application.html.haml

    !!!
    %html
      %head
        -# your header content
      %body
        .content
          = yield
    

    布局/single_column.html.haml

    = inside_layout do
      .middle
        = yield        
    

    布局/two_column.html.haml

    = inside_layout do
      .left
        -# your shared left content
      .right
        = yield        
    

    列布局现在可以像普通布局一样使用,但它们嵌套在主产量中。如果您在 inside_layout 调用中命名布局,您甚至可以创建更多嵌套在嵌套布局中的布局。

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2013-08-13
      • 2017-12-10
      • 2023-04-04
      • 2012-07-08
      相关资源
      最近更新 更多