[英]Is there a way to use a Ruby loop inside of HAML's :javascript region?
Inside of HAML, can we have a loop inside the :javascript region? 在HAML内部,我们可以在:javascript区域内有一个循环吗?
This will work: 这将有效:
- 10.upto(20) do |i|
:javascript
document.getElementById('aDiv').innerHTML += '#{i}';
and this will not: 这不会:
:javascript
- 10.upto(20) do |i|
document.getElementById('aDiv').innerHTML += '#{i}';
can the code above also be made to work as well? 上面的代码也可以工作吗?
%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. 如您所见,大的#{...}
块(可能跨越多行)运行任意Ruby代码。 The result of the last expression (in this case the map{...}.join
) is converted to a string and placed in the output. 最后一个表达式的结果(在本例中为map{...}.join
)将转换为字符串并放在输出中。
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: 编辑Radek :如果你想在Haml模板中声明一个变量,在你的JavaScript过滤器里面(这似乎是一个奇怪的愿望),那么你需要确保块to_s
的结果不会产生不需要的输出:
This Haml... 这个哈姆...
%p
:javascript
var foo = 12;
#{x = 42}
var bar = #{x};
...produces this HTML: ...生成这个HTML:
<p>
<script type='text/javascript'>
//<![CDATA[
var foo = 12;
42
var bar = 42;
//]]>
</script>
</p>
Whereas this Haml... 这个哈姆......
%p
:javascript
var foo = 12;
#{x = 42; ""}
var bar = #{x};
...produces this HTML... ...生成这个HTML ...
<p>
<script type='text/javascript'>
//<![CDATA[
var foo = 12;
var bar = 42;
//]]>
</script>
</p>
But before you do this, ask yourself: why am I creating complex Ruby variables in my view? 但在你这样做之前,先问问自己:为什么我在视图中创建复杂的Ruby变量?
Shouldn't this variable have been declared by my controller? 这个变量不应该由我的控制器声明吗?
this one works 这个有效
%script
- 10.upto(20) do |i|
document.getElementById('aDiv').innerHTML += '#{i}';
Just wanted to add that the following gets you the type and CDATA, but without the funky behaviour of :javascript (I just had to implement something like this). 只是想补充一点,下面的内容可以获得类型和CDATA,但没有时髦的行为:javascript(我只需实现类似的东西)。
%script{ :type => 'text/javascript' }
\//<![CDATA[
- (10..20) do |i|
document.getElementById('aDiv').innerHTML += '#{i}';
\//]]>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.