Mel Mel - 4 months ago 17
Ruby Question

Rails - how to add css to a helper method

Im trying to move a long if statement out of my view and into a helper method.

I currently have:

module ProfilesHelper
def items_for_profile_menu(profile)
if current_user = @profile.user_id
"<li class="col-xs-4 col-sm-2 nopadding menuitem" style="background:#006F7F">
<a href="index.html" class="hvr-sweep-to-bottom">
# link_to dashboard_path(@profile.dashboard)
<span>Dashboard</span>
</a>

</li>

<li class="col-xs-4 col-sm-2 nopadding menuitem" style="background:#39AFBF">
<a href="#resume" class="hvr-sweep-to-bottom">
<!-- <i class="flaticon-graduation61"></i> --><br><br>
<span>Timeline</span></a>
</li>"

<% else %>

"<li class="col-xs-6 col-sm-3 nopadding menuitem orange">
<a href="#stats" class="hvr-sweep-to-bottom"><i class="flaticon-placeholders4"></i><span>Impact</span></a>
</li>
<li class="col-xs-6 col-sm-3 nopadding menuitem red">
<a href="#feedback" class="hvr-sweep-to-bottom"><i class="flaticon-earphones18"></i><span>Feedback</span></a>
</li>"
<% end %>

end


end


Im getting stuck figuring out whether I can write css in the helper itself? If I can, how can I learn about the modifications required to get it working? In the view I was able to write: background:#006F7F in the list item. If I add that to the helper - then the # is received as a comment.

Can anyone see how to setup a helper method with CSS?

Answer

You are not terminating string properly in your code. One double quote (") will terminate previous double quote ("). So your string is consider like "<li class=" as one string and looking for " after that and you will get error if this is not the case.

So for declaring class inside a big string use single quotes (') inside a big double quoted (") string and concat each big string with (+).

To add class use single quote "<li class='col-xs-4 col-sm-2 nopadding menuitem'>Hi </li>" + "<li class='col-xs-4 col-sm-2 nopadding menuitem'>Hello </li>"

Change your code like below.

module ProfilesHelper
  def items_for_profile_menu(profile)
    if current_user = @profile.user_id 
      "<li class='col-xs-4 col-sm-2 nopadding menuitem' style='background:#006F7F'>
        <a href='index.html' class='hvr-sweep-to-bottom'>
          <span>Dashboard</span></a>
      </li>
      <li class='col-xs-4 col-sm-2 nopadding menuitem' style='background:#39AFBF'>
        <a href='#resume' class='hvr-sweep-to-bottom'>
        <span>Timeline</span></a>
      </li>"
    else
      "<li class='col-xs-6 col-sm-3 nopadding menuitem orange'>
        <a href='#stats' class='hvr-sweep-to-bottom'><i class='flaticon-placeholders4'></i><span>Impact</span></a>
      </li>
      <li class='col-xs-6 col-sm-3 nopadding menuitem red'>
        <a href='#feedback' class='hvr-sweep-to-bottom'><i class='flaticon-earphones18'></i><span>Feedback</span></a>
      </li>"
    end
  end

end