admin管理员组

文章数量:1277900

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?

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?

Share Improve this question edited Feb 16, 2019 at 22:17 halfer 20.5k19 gold badges108 silver badges202 bronze badges asked Feb 17, 2014 at 9:31 sameera207sameera207 16.6k19 gold badges91 silver badges154 bronze badges 1
  • Except the possible typo my_method with me_method I can't find anything wrong. – Billy Chan Commented Feb 17, 2014 at 9:35
Add a ment  | 

3 Answers 3

Reset to default 6

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

Your code:

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

Possible Solution:

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

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?

Just like you would do in a ruby string :

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

本文标签: How can I use a Ruby variable in an inline JavaScript in hamlStack Overflow