Ruby-on-rails 如何在布局外的 erb 中包含 css 或 javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/480288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:55:39  来源:igfitidea点击:

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

ruby-on-railsviewerb

提问by Matt Briggs

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

对不起,我正在编写我的第一个 Rails 应用程序。

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.erbI want products_edit.css, but I don't want that css for all product views, what is the best practice to accomplish that?

我知道布局视图的想法,但是如果您正在使用它们,有没有办法包含视图特定的 js 或 css 文件?例如,我有layouts/products.html.erb, 并且products/edit.html.erb我想要products_edit.css,但我不希望所有产品视图都使用该 css,实现这一目标的最佳实践是什么?

回答by Samuel

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

如果你有一个通用的 edit.css 文件,我会建议在你的布局中使用 if

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

Otherwise you can use content_forwith a yieldto add additional tags into the head.

否则,您可以使用content_forwithyield将其他标签添加到头部。

layout.html.erb

layout.html.erb

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

products/edit.html.erb

products/edit.html.erb

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

回答by erik

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

您可以通过执行以下操作在布局的 head 标记内添加样式表标记:

layouts/products.html.erb:

布局/products.html.erb:

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

products/edit.html.erb

产品/edit.html.erb

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

回答by Otto

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

如果你的</head>标签在你的布局中,你就不能。

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.

检查 API 文档,您可以使用该布局方法的条件做一些复杂的事情。