繁体   English   中英

Ruby on Rails如何将JavaScript放在head标签内?

[英]Ruby on Rails how to put javascript inside head tag?

我正在使用ruby 2 / rails 4,并尝试将我的JavaScript放在<head>但是所有javascript都将在页面的结尾,

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

在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...

或将此代码放在app / views / index.html.haml的末尾:

- content_for :head do
  :javascript
    //code...

这两个选择对我不起作用,有人可以给我带来启发吗?

有两种方法:

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

    !!! %html%head%meta {内容:'text / html; charset = utf-8','http-equiv'=>'Content-Type'}%meta {content:'文本',名称:'描述'}

     yield :head 

在页面app / views / home / index.html.haml中,您可以使用content_for方法:

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

2。

%script{ type: 'text/javascript }
  console.log('test');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM