【问题标题】:Ruby on Rails how to put javascript inside head tag?Ruby on Rails 如何将 javascript 放入 head 标签中?
【发布时间】:2014-01-30 19:38:15
【问题描述】:

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

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

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

这两个选项对我不起作用,有人可以给我点灯吗?

【问题讨论】:

  • 为什么要在布局文件中添加代码而不是使用 javascript_include_tag 和/或 application.js?

标签: javascript ruby-on-rails ruby-on-rails-4 haml


【解决方案1】:

两种方法:

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

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

    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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2016-10-17
    • 2012-09-15
    • 2012-07-05
    • 1970-01-01
    • 2012-07-20
    • 2012-10-02
    相关资源
    最近更新 更多