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

后端 未结 3 556
面向向阳花
面向向阳花 2020-12-13 19:47

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 includ

相关标签:
3条回答
  • 2020-12-13 20:18

    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 %>
    
    
    0 讨论(0)
  • 2020-12-13 20:28

    You can't if your </head> tag is in your layout.

    You may want a different layout for that controller action. Like this on the render:

     render :action => "index", :layout => "some_other_layout
    

    Also you can set a different default layout for a whole controller with this line in the controller class:

    layout "some_other_layout"
    

    Check the API docs, there's some complex things you can do with conditionals on that layout method.

    0 讨论(0)
  • 2020-12-13 20:36

    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 -%>
    
    0 讨论(0)
提交回复
热议问题