how to run ruby in haml in javascript definition?

后端 未结 2 1453
野趣味
野趣味 2021-02-07 23:56
  • how can I run ruby code inside javascript in haml?
  • if I use var = #{message} in my example I get undefined local variable or method message
2条回答
  •  孤独总比滥情好
    2021-02-08 00:22

    First, let's review what you seem to know:

    1. Ruby requires you to define local variables before you use them.
    2. You can run Ruby code on lines outside of a filter using - ....
    3. You use #{...} markup to interpolate Ruby code inside a filter.

    You say you want to run each, but presumably you want output from this; since the result of #{...} is turned into a string and put in your code, what you really want (probably) is map:

    %html
      %head
        :javascript
          var foo = [];
          #{
            limit = rand(4)+3
            array = (0..limit).to_a
            array.map{ |i| "foo[#{i}] = #{rand(12)};" }.join ' '
          }
          console.log(foo.length);
        %body
    

    Running the above code gives this output:

    
      
        
        
      
    
    

    As you can see, the big #{...} block (which may span multiple lines) runs arbitrary Ruby code. The result of the last expression (in this case the map{...}.join) is converted to a string and placed in the output.

提交回复
热议问题