grautur
grautur

Reputation: 30475

Sinatra/Haml: How to execute Ruby code inside Javascript?

I'm writing a Sinatra + Haml app, and in my Javascript code, I want to be execute some Ruby. In erb, the following works:

<script type="text/javascript"> 
  $(function() {
    <% @persons.each do |person| %>
        $("#<%= person.id %>").attr("style", "<%= person.style %>");
    <% end %>
  });
</script>

But how would I write this in Haml? I tried something like

:javascript
  $(function() {
    - @persons.each do |person|
      $("##{person.id}").attr("style", "#{person.style}");
  });

But the Ruby code gets rendered as code instead of getting executed.

Upvotes: 1

Views: 4588

Answers (3)

noli
noli

Reputation: 15996

:javascript
  $(function() {
    #{- @persons.each do |person|}
      $("##{person.id}").attr("style", "#{person.style}");
  });

Upvotes: 1

Ian Dickinson
Ian Dickinson

Reputation: 13295

I've had the same issue. Basic string interpolation seems to work, but nothing complex. What I've adopted is:

-v = "##{person.id}").attr("style", "#{person.style}"
:javascript
  $(function() {
    - @persons.each do |person|
      $(#{v});
  });

Upvotes: 1

JAiro
JAiro

Reputation: 5999

take a look a this post, maybe It could be helpfull.

Ruby methods within Javascript within HAML

Upvotes: 0

Related Questions