无法使用 Rails 上的自定义布局访问视图上的实例变量
Cannot access instance variable on view using custom layout on Rails
我有一个带有自定义布局的控制器方法,但我无法访问相应视图上的实例变量。
当我改回默认的应用程序布局时。我可以访问实例变量。
pages_controller.rb
def payment_summary
render layout: "content"
if session[:new_company_id].present?
@company = Company.find(session[:new_company_id])
end
@var = "this is test"
end
payment_summary.html.erb
<div class="row">
<div class="col-sm">
Company Info
<div class="card">
<%= @company.name %>
<%= @var %>
</div>
</div>
<div class="col-sm">
Due Today
</div>
</div>
layouts/content.html.erb
<!DOCTYPE html>
<html>
<head>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<!-- Font Awesome 5 Free -->
<script src="https://kit.fontawesome.com/9da10782cc.js"></script>
<!-- for js cookie use -->
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
</head>
<body class="content-pages <%= body_class %>">
<%= yield %>
</body>
</html>
当我删除时,渲染布局内容一切正常。
render
在这种情况下是 "order dependent"。将其向下移动,作为操作主体中的最后一条语句:
def payment_summary
if session[:new_company_id].present?
@company = Company.find(session[:new_company_id])
end
@var = "this is test"
render layout: "content"
end
我有一个带有自定义布局的控制器方法,但我无法访问相应视图上的实例变量。
当我改回默认的应用程序布局时。我可以访问实例变量。
pages_controller.rb
def payment_summary
render layout: "content"
if session[:new_company_id].present?
@company = Company.find(session[:new_company_id])
end
@var = "this is test"
end
payment_summary.html.erb
<div class="row">
<div class="col-sm">
Company Info
<div class="card">
<%= @company.name %>
<%= @var %>
</div>
</div>
<div class="col-sm">
Due Today
</div>
</div>
layouts/content.html.erb
<!DOCTYPE html>
<html>
<head>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<!-- Font Awesome 5 Free -->
<script src="https://kit.fontawesome.com/9da10782cc.js"></script>
<!-- for js cookie use -->
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
</head>
<body class="content-pages <%= body_class %>">
<%= yield %>
</body>
</html>
当我删除时,渲染布局内容一切正常。
render
在这种情况下是 "order dependent"。将其向下移动,作为操作主体中的最后一条语句:
def payment_summary
if session[:new_company_id].present?
@company = Company.find(session[:new_company_id])
end
@var = "this is test"
render layout: "content"
end