在Rails应用程序中,我们可以通过控制器中的实例变量来将数据传递给视图。然而,这些实例变量默认情况下在应用布局中是不可访问的。要解决这个问题,我们可以使用Rails的helper方法来在布局中访问这些变量。
以下是一个解决方法的示例代码:
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :set_global_variables
def set_global_variables
@global_variable = "This is a global variable"
end
end
# app/helpers/application_helper.rb
module ApplicationHelper
def global_variable
@global_variable
end
end
My Application
My Application
<%= global_variable %>
<%= yield %>
在上面的代码中,我们在应用的基础控制器ApplicationController
中定义了一个set_global_variables
方法,该方法设置了一个实例变量@global_variable
。然后,我们在ApplicationHelper
模块中定义了一个名为global_variable
的helper方法,该方法返回@global_variable
的值。最后,在应用布局的视图中,我们可以通过调用global_variable
方法来访问@global_variable
的值。
这样,我们就可以在应用布局中访问控制器中定义的实例变量了。
上一篇:ApplicationAutoScaling如何用于Lambda?
下一篇:ApplicationConfigurationMetadataResolver : 无法获取Docker资源的属性。