简体   繁体   English

如何在Rails 4中的javascript中包含ruby变量?

[英]How do I include ruby variables in javascript in Rails 4?

I have a rails application which is serving up a number of views which include specific data from the database to be manipulated by some javascript, specifically for use with Chartjs. 我有一个rails应用程序,它提供了许多视图,其中包括来自数据库的特定数据,这些数据将由一些javascript操作,特别是用于Chartjs。

Options I have explored are: 我探讨的选项是:

  1. Use an ajax call to pull the data off the server. 使用ajax调用从服务器中提取数据。 I don't like this one because the user isn't changing any data, I have access to all the data when I render the page, there ought to be a better way. 我不喜欢这个,因为用户没有更改任何数据,我在呈现页面时可以访问所有数据,应该有更好的方法。
  2. Use <script> tags in the view ERB and simply have ERB interpolate the variable. 在视图ERB中使用<script>标记,只需让ERB插入变量即可。 This seems a little hacky and definitely doesn't take advantage of all my beautiful haml. 这似乎有点hacky,绝对没有利用我所有美丽的haml。 But it is easy and allows me to put javascript variables on the page which can then be picked up after the document.onload. 但它很容易,并允许我在页面上放置javascript变量,然后可以在document.onload之后获取。
  3. Gon. 刚。 Great gem and very easy. 伟大的宝石,非常容易。 But should this really require a gem? 但这真的需要宝石吗?

I feel as though the solution should involve the asset pipeline and some sort of rails interpolation, but I can't seem to make that work very cleanly. 我觉得解决方案应该涉及资产管道和某种轨道插值,但我似乎无法使这项工作非常干净。 What is the elegant rails 4 way for solving this? 什么是优雅的轨道4解决这个问题?

Thanks everyone! 感谢大家!

There are many ways to pass data from server-side to javascript, I'll list two of the most common (that don't use a gem or other external tools) below: 有很多方法可以将数据从服务器端传递到javascript,我将在下面列出两种最常见的(不使用gem或其他外部工具):

  1. Use the second method you described, and interpolate ERB tags inside the javsacript. 使用您描述的第二种方法,并在javsacript中插入ERB标记。 This is ugly, hacky and is not even close to best practice. 这是丑陋的,hacky,甚至没有接近最佳实践。

  2. Use data attributes. 使用数据属性。 You can modify your HAML to include additional attributes, like "data-my-variable", and access it via javascript (example using jQuery: $(element).data("my-variable") ). 您可以修改HAML以包含其他属性,例如“data-my-variable”,并通过javascript访问它(例如使用jQuery: $(element).data("my-variable") )。

The data attribute method is, in my opinion, the cleanest way of doing this, it's exactly the purpose of data attributes. 在我看来,数据属性方法是最干净的方法,它正是数据属性的目的。

Now, I don't know HAML, I've only worked with ERB before, but I found this answer by Mandeep , which explains how you can add data attributes to your HAML: 现在,我不知道HAML,我之前只和ERB合作,但是我发现了Mandeep的这个答案 ,它解释了如何向HAML添加数据属性:

%a{"data-my-variable" => "my data", href: "#"}

OR 要么

%a{href: "#", :data => {:my_variable => "my data"}}

EDIT : Sorry, I found your question along with other, newer, questions, I just assumed it was recent, and not from over a year ago :) 编辑 :对不起,我发现你的问题以及其他更新的问题,我只是假设它是最近的,而不是一年多以前:)

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

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