Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

erb how to loop on array

I can't simply loop on an array with ruby erb template system...

here is my template:

<% ['foo', 'bar'].each do |val| -%>
<%= val %>
<% end -%>

Here is the command line and the result

erb test.erb
/usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:896:in `eval': test.erb:1: syntax error, unexpected ';' (SyntaxError)
'foo', 'bar'].each do |val| -; _erbout.concat "\n"
                              ^
test.erb:3: syntax error, unexpected ';'
;  end -; _erbout.concat "\n"
         ^
        from /usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:896:in `result'
        from /usr/share/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/erb.rb:878:in `run'
        from /usr/share/rvm/rubies/ruby-2.4.1/bin/erb:149:in `run'
        from /usr/share/rvm/rubies/ruby-2.4.1/bin/erb:170:in `<main>'

What is wrong with this really simple example?

Disclaimer: I am a ruby and erb noob ^^

like image 909
nemenems Avatar asked Oct 16 '25 18:10

nemenems


2 Answers

You're not supposed to have those "-" at the end before the "%".

<% ['foo', 'bar'].each do |val| %>
    <%= val %>
<% end %>

This should work.

like image 120
Oli Crt Avatar answered Oct 18 '25 14:10

Oli Crt


You have to set trim mode to -:

$ erb -T - test.erb
foo
bar

From the man page:

-T mode   Specifies trim mode (default 0). mode can be one of
          0   EOL remains after the embedded ruby script is evaluated.
          1   EOL is removed if the line ends with %>.
          2   EOL is removed if the line starts with <% and ends with %>.
          -   EOL is removed if the line ends with -%>. And leading whitespaces
              are removed if the erb directive starts with <%-.
like image 27
Stefan Avatar answered Oct 18 '25 13:10

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!