Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
RubyonRails如何将javascript放入head标记中?_Javascript_Ruby On Rails_Ruby On Rails 4_Haml - Fatal编程技术网

RubyonRails如何将javascript放入head标记中?

RubyonRails如何将javascript放入head标记中?,javascript,ruby-on-rails,ruby-on-rails-4,haml,Javascript,Ruby On Rails,Ruby On Rails 4,Haml,我正在使用ruby 2/rails 4,并试图将我的javascript放入其中,但所有的Java脚本都将在页面的末尾 我正在尝试使用此代码,但不起作用: 在app/views/layouts/index.html.haml中: !!! %html %head %meta{ content: 'text/html; charset=utf-8', 'http-equiv' => 'Content-Type' } %meta{ content: 'text', name:

我正在使用ruby 2/rails 4,并试图将我的javascript放入其中,但所有的Java脚本都将在页面的末尾

我正在尝试使用此代码,但不起作用:

在app/views/layouts/index.html.haml中:

!!!
%html
  %head
    %meta{ content: 'text/html; charset=utf-8', 'http-equiv' => 'Content-Type' }
    %meta{ content: 'text', name: 'description'}
    :javascript
      //code...
- content_for :head do
  :javascript
    //code...
或者将此代码放在app/views/index.html.haml的末尾:

!!!
%html
  %head
    %meta{ content: 'text/html; charset=utf-8', 'http-equiv' => 'Content-Type' }
    %meta{ content: 'text', name: 'description'}
    :javascript
      //code...
- content_for :head do
  :javascript
    //code...
这两种选择对我不起作用,有人能给我带来光明吗?

有两种方法:

我认为您必须在head中定义yield:head,然后您可以在页面中使用content_for:head do块

!!! %html %头 %meta{content:'text/html;charset=utf-8','http-equiv'=>'content-Type'} %meta{content:'text',name:'description'}

yield :head
在app/views/home/index.html.haml页面中,您可以使用content_作为方法:

- content_for :head do
  :javascript
     console.log('test');
二,


为什么要向布局文件中添加代码而不是使用javascript_include_标记和/或application.js?