sameera207
sameera207

Reputation: 16619

How can I use a Ruby variable in an inline JavaScript in haml?

I have the following variable in my controller:

class MyController < ApplicationController

  def my_method
    @status = "status"
  end
end

In my haml view, I tried following, but it doesn't work (since it's using the default .erb syntax):

#app/views/mycontroller/me_method.html.haml

:javascript
  alert(<%=raw @status %>)

How can I use the @status variable inside my inline JavaScript?

Upvotes: 5

Views: 3927

Answers (3)

Vageesh Bhasin
Vageesh Bhasin

Reputation: 553

You can use the simple "#{}" interpolation tags to use ruby variables with HAML.

Your code:

:javascript
    alert(<%=raw @status %>)

Possible Solution:

:javascript
    alert("#{@status}")

Upvotes: 5

Intrepidd
Intrepidd

Reputation: 20868

Just like you would do in a ruby string :

:javascript
  alert("#{raw @status}")

Upvotes: 2

user513951
user513951

Reputation: 13612

Use the normal string interpolation syntax (#{}).

#app/views/mycontroller/me_method.html.haml

:javascript
  alert(#{raw @status})

See also this previous SO question:

Inline ruby in :javascript haml tag?

Upvotes: 3

Related Questions