1

I am trying to pass data from my haml views to javascript. In my welcome controller I have index method. In my index.html.haml view file I have the below:

:javascript
  window.putalert = "#{ "Data" }";

and in my welcome.js.coffee I have:

jQuery ->
        alert putalert

However, the above is not working. I am getting Uncaught ReferenceError: putalert is not defined.

Any suggestions on how to solve this?

The error message in chrome debugging is

(function() {

  jQuery(function() {
    return alert(putalert);
Uncaught ReferenceError: putalert is not defined
  });

}).call(this);
  • possible duplicate of [Injecting variable values into javascript and HAML in RoR](http://stackoverflow.com/questions/4708369/injecting-variable-values-into-javascript-and-haml-in-ror) – Ciro Santilli OurBigBook.com Jun 27 '14 at 08:26

2 Answers2

3

You can inject javascript with the :javascript haml tag. You can insert Ruby with #{}. Try something like this:

:javascript
  window.putalert = "#{ "Data" }";

You could even insert coffeescript in your views if you want (You have to use tilt for this):

:coffee
  @putalert = "#{ "Data" }"

Here a reference of the haml filters: http://haml.info/docs/yardoc/file.REFERENCE.html

Michael Koper
  • 9,586
  • 7
  • 45
  • 59
  • Hi, `:javascript window.putalert = "#{ "Data" }";` is not working. I am still getting the Uncaught ReferenceError: putalert is not defined error. –  Feb 22 '13 at 16:29
0

One really nice way to handle data for JavaScript in general is to use the data attributes on HTML tags. Then using something like jQuery you can pull that info. It's a little cleaner than injecting it into the js.

More info: http://ejohn.org/blog/html-5-data-attributes/

Austin Lin
  • 2,545
  • 17
  • 17