Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 770
Matt Briggs Avatar asked Jan 26 '09 16:01

Matt Briggs


2 Answers

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 -%> 
like image 147
Samuel Avatar answered Sep 18 '22 22:09

Samuel


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 %>  
like image 37
erik Avatar answered Sep 17 '22 22:09

erik