新手问题 如何在 application.html.erb 里面定义变量在所有的页面里面都能用

nicetyler · August 15, 2017 · Last by small_fish__ replied at August 16, 2017 · 2304 hits
<!DOCTYPE html>
<html>
  <head lang="en">
    <%= favicon_link_tag %>
    <%= csrf_meta_tags %>
    <title><%= yield(:title) %> </title>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body id="f">
  <%= render 'layouts/header' %>
    <%= yield %>
  <%= @list_hs %>
  <%= render 'layouts/footer' %>
  </body>
</html>

这个 applition.html.erb 里面有个@list_hs,这个变量在哪里赋值和定义啊,好像没有专门的控制器

ApplicationController

Reply to zouyu

直接在那个控制器里面定义变量好像显示不出来啊

你贴的代码是 layouts/applition.html.erb 吧,@list_hs 是你访问的 controller 下的 action 里定义的

我的想法: 你在 application_controller.rb 里面写个 action, 例:

def get_list_hs
    return  XXX
end

之后在你访问的 action 里加上

@list_hs = get_list_hs

先提条件是 你的 controller < ApplicationController

在 ApplicationController 中:

before_action :xxoo

def xxoo
  @list_hs = ...
end
5 Floor has deleted

application_helper 里面抽个方法

比如:

def list_hs
  @list_hs ||= xxxxx
end

然后 template 里面可以

<%=list_hs.xxx%>
You need to Sign in before reply, if you don't have an account, please Sign up first.