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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, :javascript window.putalert = "#{ "Data" }"; is not working. I am still getting the Uncaught ReferenceError: putalert is not defined error.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.