How to include a css or javascript in an erb that is outside the layout?

43,168

Solution 1

If you have a generic edit.css file, I would suggest an if in your layout

<%= stylesheet_link_tag 'edit' if params[:action] == 'edit' %>

Otherwise you can use content_for with a yield to add additional tags into the head.

layout.html.erb

<head>
  ...
  <%= yield(:header) if @content_for_header %>
</head>

products/edit.html.erb

<% content_for :header do -%>
  <%= stylesheet_link_tag 'edit_product' %>
<% end -%>

Solution 2

You can add a stylesheet tag inside the head tag of the layout by doing something like this:

layouts/products.html.erb:


    <head>
        ...
        <%= yield :css %>
        ...
    </head>

products/edit.html.erb


<% content_for :css do
    stylesheet_link_tag 'products_edit'
end %>

Share:
43,168

Related videos on Youtube

Rinzler
Author by

Rinzler

I have experience in JSP/Java/Oracle, and ASP.net/C#/Sql Server. I am a rubyist, a clojurian, a rustacean, and work with rails professionally. I would consider myself a javascript programmer, and my expertise is front end web development. I am also a big fan of both emacs and parts of vim. You can read my blog at http://mattbriggs.net

Updated on July 09, 2022

Comments

  • Rinzler
    Rinzler almost 2 years

    Sorry for the slightly noobish question, as I am writing my first rails app.

    I get the idea of the layout view, but if you are using them, is there any way to include a view specific js or css file? For example, I have layouts/products.html.erb, and for products/edit.html.erb I want products_edit.css, but I don't want that css for all product views, what is the best practice to accomplish that?

  • Samuel
    Samuel over 15 years
    -1, you are wrong. Using yield(:header) and content_for :header you can specify additional content for the head tag.
  • erik
    erik over 15 years
    I'm not sure you want '<%=' on the stylesheet_link_tag line. You don't want to output that on the edit view.
  • Otto
    Otto over 15 years
    That doesn't change the fact that the rest of it is perfect legitimate solution to the problem.
  • Samuel
    Samuel over 15 years
    No, but it violates the DRY principle that rails loves so much.
  • Otto
    Otto over 15 years
    How so? I can resolve duplication in the layouts via partials, if there's enough of it. I'd say your solution pushes too much knowledge of the layout down into the templates that ought to be ignorant of what they're contained in, aside from a clearly delineated contract.
  • Otto
    Otto over 15 years
    Again, if there's a lot of duplication between layouts, I can use partials to resolve it. And I didn't down vote you.
  • Natan Yellin
    Natan Yellin over 12 years
    In Rails 3.0, you need to use if content_for? :header, not @content_for_header
  • Roman Pushkin
    Roman Pushkin over 6 years
    In Rails 5 worked for me without if @content_for_header