【问题标题】:how to use a controller variable in my layout如何在我的布局中使用控制器变量
【发布时间】:2012-12-27 12:00:11
【问题描述】:

我正在尝试在布局中使用控制器的变量。

例如:
@posts = Post.all.count

在我的布局中,我想列出 Post 计数,即使我打开另一个控制器的索引视图。

非常感谢!!!

【问题讨论】:

    标签: layout controller ruby-on-rails-3


    【解决方案1】:

    两种解决方案:

    • 在您的布局中使用<%= Post.all.count %>
    • 在您的 ApplicationController 中添加一个 before_filter 以加载变量。

      class ApplicationController < ActionController::Base
        before_filter :load_layout_variables
      
      protected
        def load_layout_variables
          @posts = Post.all.count
        end
      end
      

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      相关资源
      最近更新 更多