开发者

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.


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});
  });


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


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

Ruby methods within Javascript within HAML

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜