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:
- Ruby requires you to define local variables before you use them.
- You can run Ruby code on lines outside of a filter using
- ...
. - 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
How to Match a Whole Word in JavaScript
How to Remove Item from Array by Value
For Loop For Htmlcollection Elements
Merge Two Array of Objects Based on a Key
How to Get the Difference Between Two Dates in JavaScript
Best Way to Find If an Item Is in a JavaScript Array
How to Find the Operating System Details Using JavaScript
Angularjs Routing Without the Hash '#'
I Keep Getting "Uncaught Syntaxerror: Unexpected Token O"
Converting a Js Object to an Array Using Jquery
Variable Name as a String in JavaScript
Difference Between Two Dates in Years, Months, Days in JavaScript
Why Is Null an Object and What's the Difference Between Null and Undefined
How to Detect My Browser Version and Operating System Using JavaScript
Jquery Selector for Inputs with Square Brackets in the Name Attribute