简体   繁体   English

Rails局部渲染

[英]Rails partial rendering

What is the best way to render partial depending on current controller? 取决于当前控制器的部分渲染的最佳方法是什么?
For example we have got this partial: 例如,我们有这个部分:
<h2>Funny <em>title</em></h2> And depending on controller i'd like to change <em> into <strong> <h2>Funny <em>title</em></h2>并且根据控制器的不同,我想将<em>更改为<strong>
We can do this by passing locals to partial and use conditional: 我们可以通过将locals传递给partial并使用条件来做到这一点:
<% if :controller == "something" tag="em" elsif :controller == "other" tag="strong" %>
<h2>Funny <<%= tag %>>title</<%= tag %>></h2>

But what if there are n controllers? 但是如果有n个控制器怎么办? That number of conditions in view doesn't look good. 如此数量的条件看起来并不理想。

I would just set an instance variable in a before_filter and then grab it in the partial. 我只是在before_filter中设置一个实例变量,然后在局部变量中抓取它。

For instance, in your controller: 例如,在您的控制器中:

class FooController ...
  before_filter set_subtitle_flag

  ...

  private

  def set_subtitle_flag
    @subtitle_strong = true
  end
end

Then in your partial: 然后在您的部分:

<% if @subtitle_strong %>
  <strong>Foo bar baz</strong>
<% else %>
  <em>Foo bar baz</em>
<% end %>

One option is to not use server-side logic, but to use CSS. 一种选择是不使用服务器端逻辑,而使用CSS。

Instead of: 代替:

<h2>Funny <em>title</em></h2>

You could wrap your title in a span tag and style that with a dynamic CSS class name based upon your controller name: 您可以将标题包装在span标签和样式中,并根据您的控制器名称使用动态CSS类名称:

<h2>Funny <span class="<%= title_class %>">title</span></h2>

Pass the controller name to the partial as a local variable called ' title_class ' and have CSS selector variations to match these names in your stylesheet. 将控制器名称作为名为“ title_class ”的局部变量传递给局部变量,并具有CSS选择器变体以匹配样式表中的这些名称。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM