Ruby code in Haml

C

cz

Hi:

How do I embed Ruby code in Haml? I am passing an array via a get
request. The array can be displayed using
%p #{@ary}

However, if I try..

for x in 0...#{@ary.length}
print #{@ary.at(x)}
end

I get an error, undefined variable x. What is going on?

cz
 
J

James Brister

Hi:

How do I embed Ruby code in Haml? I am passing an array via a get
request. The array can be displayed using
%p #{@ary}

However, if I try..

for x in 0...#{@ary.length}
print #{@ary.at(x)}
end

I get an error, undefined variable x. What is going on?

cz

You need '-' at the start of a line with ruby code otherwise haml just
passes it through Also indentation is important.

- for x in (e-mail address removed)
#{@ary.at(x)}

e.g.

% (echo '- for x in 0..5' ; echo ' #{x}') | haml
1
2
3
4
5

you don't need the 'end' that you do in normal ruby as the indentation
defines the block (much like in python).
 
B

Brian Candler

James Brister wrote in post #982179:
You need '-' at the start of a line with ruby code otherwise haml just
passes it through Also indentation is important.

- for x in (e-mail address removed)
#{@ary.at(x)}

I think it's clearer to use regular HAML insertion inside the block,
instead of ruby string expansion:

- for x in (e-mail address removed)
= @ary.at(x)

And of course, "each" is better here.

- @ary.each do |elem|
= elem

Standalone example, showing some nested tags:

$ haml <<EOS
- @ary = [1,4,9,16]
- @ary.each do |elem|
%tr
%td= elem
EOS

Output:

<tr>
<td>1</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr>
<td>9</td>
</tr>
<tr>
<td>16</td>
</tr>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,217
Latest member
topweb3twitterchannels

Latest Threads

Top