开发者

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

开发者 https://www.devze.com 2023-03-18 20:53 出处:网络
I\'m writing a Sinatra + Haml app, and in my Javascript code, I want to be execute some Ruby. In开发者_运维百科 erb, the following works:

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

精彩评论

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