How to include a css or javascript in an erb that is outside the layout?
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 %>
Related videos on Youtube
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, 2022Comments
-
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 forproducts/edit.html.erb
I wantproducts_edit.css
, but I don't want that css for all product views, what is the best practice to accomplish that? -
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 over 15 yearsI'm not sure you want '<%=' on the stylesheet_link_tag line. You don't want to output that on the edit view.
-
Otto over 15 yearsThat doesn't change the fact that the rest of it is perfect legitimate solution to the problem.
-
Samuel over 15 yearsNo, but it violates the DRY principle that rails loves so much.
-
Otto over 15 yearsHow 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 over 15 yearsAgain, 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 over 12 yearsIn Rails 3.0, you need to use
if content_for? :header
, not@content_for_header
-
Roman Pushkin over 6 yearsIn Rails 5 worked for me without
if @content_for_header