Is there a way to use a Ruby loop inside of HAML's :javascript region?

前端 未结 3 2258
日久生厌
日久生厌 2020-12-11 01:07

Inside of HAML, can we have a loop inside the :javascript region?

This will work:

- 10.upto(20) do |i|
  :javascript
    document.getElementById(\'aD         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 02:12

    %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.

    Edit for Radek: If you want to declare a variable inside you Haml template, inside your JavaScript filter (which seems like an odd desire), then you need to be sure that the result of the block to_s doesn't produce unwanted output:

    This Haml...

    %p
      :javascript
        var foo = 12;
        #{x = 42}
        var bar = #{x};
    

    ...produces this HTML:

    Whereas this Haml...

    %p
      :javascript
        var foo = 12;
        #{x = 42; ""}
        var bar = #{x};
    

    ...produces this HTML...

    But before you do this, ask yourself: why am I creating complex Ruby variables in my view?
    Shouldn't this variable have been declared by my controller?

提交回复
热议问题