如何在我的布局中使用控制器变量

问题描述:

我想在我的布局中使用我的控制器的变量。如何在我的布局中使用控制器变量

例如:
@posts = Post.all.count

在我的布局,我想列出的职位数量,甚至当我打开另一个控制器的索引视图。

非常感谢!

两个解决方案:

  • 使用<%= 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 
    
+0

大。有效!我选择了第一个解决方案 – daniel 2011-01-06 13:40:41