开发者

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>

We can do this by passing locals to partial and use conditional:

<% if :controller == "something" tag="em" elsif :controller == "other" tag="strong" %>

<h2>Funny <<%= tag %>>title</<%= tag %>></h2>

But what if there are n controllers? That number of condit开发者_如何转开发ions in view doesn't look good.


I would just set an instance variable in a before_filter and then grab it in the partial.

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.

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:

<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜