[英]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: 我探讨的选项是:
<script>
tags in the view ERB and simply have ERB interpolate the variable. <script>
标记,只需让ERB插入变量即可。 This seems a little hacky and definitely doesn't take advantage of all my beautiful haml. 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或其他外部工具):
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,甚至没有接近最佳实践。
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.