在 Rails 个视图中将所选 CSS/JavaScript 添加到 Ruby
Adding selected CSS/JavaScript to Ruby on Rails views
我只想在不同的观点上添加不同的 CSS/JavaScript。显然,如果我将它们放在布局中,它们将被添加到每个视图中。另外,我不想为不同的视图创建单独的布局。
我创建了一个布局 layouts/standard.html.erb
,头部包含以下内容:
<head>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
</head>
这不会将 app/assets 文件夹中的 CSS/JavaScript 添加到呈现的页面。
我还尝试在布局中使用 <%= yield :javascript %>
,在视图中使用 javascript_include_tag 'filename' 尝试 content_for,但它给出了资产管道错误。
您可以使用控制器特定的 javascript,如 documentation 中所述:
When you generate a scaffold or a controller, Rails also generates a JavaScript file (or CoffeeScript file if the coffee-rails gem is in the Gemfile) and a Cascading Style Sheet file (or SCSS file if sass-rails is in the Gemfile) for that controller. Additionally, when generating a scaffold, Rails generates the file scaffolds.css (or scaffolds.css.scss if sass-rails is in the Gemfile.)
For example, if you generate a ProjectsController, Rails will also add a new file at app/assets/javascripts/projects.js.coffee and another at app/assets/stylesheets/projects.css.scss. By default these files will be ready to use by your application immediately using the require_tree directive. See Manifest Files and Directives for more details on require_tree.
我建议您也浏览整个页面以了解资产管道的工作原理。
我只想在不同的观点上添加不同的 CSS/JavaScript。显然,如果我将它们放在布局中,它们将被添加到每个视图中。另外,我不想为不同的视图创建单独的布局。
我创建了一个布局 layouts/standard.html.erb
,头部包含以下内容:
<head>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
</head>
这不会将 app/assets 文件夹中的 CSS/JavaScript 添加到呈现的页面。
我还尝试在布局中使用 <%= yield :javascript %>
,在视图中使用 javascript_include_tag 'filename' 尝试 content_for,但它给出了资产管道错误。
您可以使用控制器特定的 javascript,如 documentation 中所述:
When you generate a scaffold or a controller, Rails also generates a JavaScript file (or CoffeeScript file if the coffee-rails gem is in the Gemfile) and a Cascading Style Sheet file (or SCSS file if sass-rails is in the Gemfile) for that controller. Additionally, when generating a scaffold, Rails generates the file scaffolds.css (or scaffolds.css.scss if sass-rails is in the Gemfile.)
For example, if you generate a ProjectsController, Rails will also add a new file at app/assets/javascripts/projects.js.coffee and another at app/assets/stylesheets/projects.css.scss. By default these files will be ready to use by your application immediately using the require_tree directive. See Manifest Files and Directives for more details on require_tree.
我建议您也浏览整个页面以了解资产管道的工作原理。