将JavaScript添加到Rails应用程序 - HTML停止呈现

时间:2015-07-29 01:30:09

标签: javascript html ruby-on-rails d3.js

我试图通过将D3添加到Rails应用程序来到Hello World,但我无法在我的视图中获取普通的HTML进行渲染。我不想触摸controllerapplication.js文件,除了渲染HTML之外,我所做的似乎也有效...

我已将必要的JavaScript个文件添加到app/assets/javascripts

我将config/initializers/assets.rb更新为:

Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( d3.js )
Rails.application.config.assets.precompile += %w( sankey.js )
Rails.application.config.assets.precompile += %w( sankeycreate.js )

我将app/views/layouts/application.html.erb更新为:

<!DOCTYPE html>
<html>
<head>
  <title>D3app</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
  <%= yield(:head) %>
</head>
<body>
  <%= yield(:body) %>
</body>
</html>

最后,我有app/views/static_pages/home.html.erb编码:

<% content_for :head do %>
  <%= javascript_include_tag 'd3' %>
  <%= javascript_include_tag 'sankey' %>
<% end %>

<h1>D3 App</h1>
<p id="chart2">

<% content_for :body do %>
  <%= javascript_include_tag 'sankeycreate' %>
<% end %>

我将SVG创建的sankeycreate.js绑定到body标记。 SVG呈现没有问题,我没有看到任何错误,但<h1>D3 App</h1><p id="chart2">元素不会呈现。我无法弄清楚为什么会这样。

1 个答案:

答案 0 :(得分:0)

您有两个content_for块clr.dll:body,但您丢失的两个标签中没有任何一个。如果要渲染内容块之外的内容,只需在布局中使用:head,因此rails知道在何处呈现此内容。

yield

http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield