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.

3 Answers 3

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});
  });
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

I get a "syntax error, unexpected tSTRING_DEND" when I try this. Any tricks to this?
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
0

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

Ruby methods within Javascript within HAML

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.