简体   繁体   English

如何将变量从控制器传递到Rails中的布局助手

[英]How can I pass variables from a controller to a layout helper in rails

I have a quite complex design template, which has different approaches to wrap it's context. 我有一个非常复杂的设计模板,它使用不同的方法包装上下文。

I have to use 我必须用

<body>
  yield
</body>

sometimes 有时

<body>
  <div class="foo"> 
    yield
  </div>
</body>

sometimes 有时

<body>
  <div class="bar">
    <div id="breadcrumbs"> 
      some content
    </div>
    <div class="innnerwrap" id="zurb">
      yield
    </div>
  </div>
</body>

and so on 等等

I wanna be able to control them from my controller. 我想能够从我的控制器中控制它们。 I thought I make a template_helper.rb which decides what to show. 我以为我做了一个template_helper.rb来决定要显示什么。

  • Any suggestions? 有什么建议么?
  • I also wanna prevent to have 5 or more layouts if only the "wrapper" divs change 我也想避免只有“包装器” div改变时有5个或更多的布局

I see 2 approaches to this: 我看到两种解决方法:

1. Set your layout in your controller: 1.在控制器中设置布局:

class MyController < ApplicationController
  layout 'admin', :only => [:show, :index]

  # Controller methods
end

2. have 1 layout with multiple dynamic partials: 2.具有1个具有多个动态部分的布局:

layout.html.erb:
<body>
 <% if params[:controller] == 'MyController' && params[:action] == 'MyAction' %>
    <% render :partial => 'partial1' %>
 <% elsif params[:controller] == 'MyController' && params[:action] == 'MyAction2' %>
    <% render :partial => 'partial2' %>
<% elsif params[:controller] == 'MyController2' && params[:action] == 'MyAction' %>
    <% render :partial => 'partial3' %>
 <% end %>
</body>

_partial1.html.erb
<%= yield %>


_partial2.html.erb
<div class="foo"> 
    <%= yield %>
</div>

_partial2.html.erb
<div class="bar">
    <div id="breadcrumbs"> 
      some content
    </div>
    <div class="innnerwrap" id="zurb">
      <%= yield %>
    </div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将变量从Rails控制器传递到AngularJs - How to pass variables from rails controller to AngularJs 如何通过导轨将对象从一个控制器传递到另一个控制器? - How can I pass objects from one controller to another in rails? 如何将变量从一个控制器传递到另一个控制器? (铁轨) - How can I pass variable from one controller to another? (rails) 如何使用Rails将实例变量DRY保留在控制器帮助器中? - How can I keep an instance variable DRY in a controller helper with Rails? Rails:如何在助手或控制器外部访问请求对象? - Rails: how can I access the request object outside a helper or controller? 如何在不使用form_helper的情况下从Rails控制器中的表单获取值? - How can I get values from form in controller in rails without using form_helper? 如何从 Ruby on Rails 的控制台调用控制器/视图帮助器方法? - How can I call controller/view helper methods from the console in Ruby on Rails? Rails:如何从控制器传递实例变量以呈现部分 - Rails: How to pass instance variables from a controller to render partial 如何将变量从控制器传递到 Rails 5.2 中的模型? - How to pass variables from a controller to a model in Rails 5.2? 如何更改在Rails 3布局中调用的帮助程序,具体取决于控制器 - How to vary a helper called within a Rails 3 layout, depending on the controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM