1

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.

grautur
  • 29,955
  • 34
  • 93
  • 128

3 Answers3

1

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});
  });
Ian Dickinson
  • 12,875
  • 11
  • 40
  • 67
1
:javascript
  $(function() {
    #{- @persons.each do |person|}
      $("##{person.id}").attr("style", "#{person.style}");
  });
noli
  • 15,927
  • 8
  • 46
  • 62
  • I get a "syntax error, unexpected tSTRING_DEND" when I try this. Any tricks to this? – thoughtpunch Aug 14 '13 at 03:08
  • sorry.. can't remember exactly what my thought process was around this back then.. nowadays, I would probably just try to find a different way to accomplish whatever it was, as this approach is pretty messy and unmaintainble – noli Aug 14 '13 at 12:24
0

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

Ruby methods within Javascript within HAML

Community
  • 1
  • 1
JAiro
  • 5,914
  • 2
  • 22
  • 21