简体   繁体   中英

Ruby on Rails how to put javascript inside head tag?

i'm using ruby 2/rails 4 and trying to put my javascript in <head> but all javascripts is going to end of the page,

i'm trying to use this code but don't works:

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

or puting this code in the end of app/views/index.html.haml:

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

this two alternatives don't works to me, someone can bring me a light?

Two ways to do it:

  1. I think you have to define "yield :head" in the head and then you can use the content_for :head do block in your pages.

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

     yield :head 

In the page app/views/home/index.html.haml you can use content_for method:

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

2.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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