uzaif uzaif - 3 months ago 10
Ruby Question

elegant way to add css class in rails partials

I have partials which display in sidebar like below


__side_bar_partials.html.erb


<div class="col-sm-3">
<div class="account-left">
<ul>
<li class="active"><a href="menu1">Menu1</a></li>
<li><a href="menu2">Menu2</a></li>
<li><a href="menu3">Menu3</a></li>
<li><a href="menu4">Menu4</a></li>
<li><a href="menu5">Menu5</a></li>
</ul>
</div>
</div>


now what i need when i render this partial i want to add css
class
active added on selected menu

right now i render it with normal way

<%= render "profile_sidebar"%>


what i need to include in above code so it will add active class on selected menu

Answer

Basically you have 2 choices. First one is to check the current page and highlight the right menu choice.

<div class="col-sm-3">
  <div class="account-left">              
    <ul>
      <li class="<%= 'active' if current_page?(menu1_path) %>"><a href="menu1">Menu1</a></li>
      <li class="<%= 'active' if current_page?(menu2_path) %>">><a href="menu2">Menu2</a></li>
      <li class="<%= 'active' if current_page?(menu3_path) %>">><a href="menu3">Menu3</a></li>
      <li class="<%= 'active' if current_page?(menu4_path) %>">><a href="menu4">Menu4</a></li>
      <li class="<%= 'active' if current_page?(menu5_path) %>">><a href="menu5">Menu5</a></li>
    </ul>
  </div>
</div>

But since you are looking for more elegant way, I would suggest second choice: doing a separate helper for your list elements. The solution with helper is perfectly described here.

Hope it helps.

Comments