How to Use a Ruby Loop Inside of Haml's :JavaScript Region

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

this one works

%script
- 10.upto(20) do |i|
document.getElementById('aDiv').innerHTML += '#{i}';

how to run ruby in haml in javascript definition?

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:

<html>
<head>
<script type='text/javascript'>
//<![CDATA[
var foo = [];
foo[0] = 2; foo[1] = 0; foo[2] = 11; foo[3] = 8; foo[4] = 0; foo[5] = 1;
//]]>
</script>
<body></body>
</head>
</html>

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.

Inline ruby in :javascript haml tag?

You can use the string interpolation syntax (#{...}) :

:javascript
var tab = #{@tab}

Take care of correctly escaping, however.

In HAML, how to write comments in :javascript region so that comments do not show to the public?

#{}- blocks are evaluated, so you can write

#{ # this is a ruby comment, but still a comment (newline is required)
}

How to iterate over an array with HAML?

You forgot the hash symbol.

- @fonts.each do |font|
%link{:href=>"//fonts.googleapis.com/css?family=#{font}",:rel=>"stylesheet",:type=>"text/css"}
^ here


Related Topics



Leave a reply



Submit