Home erb how to loop on array
Reply: 2

erb how to loop on array

nemenems
1#
nemenems Published in 2018-02-14 10:04:47Z

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 ^^

Oli Crt
2#
Oli Crt Reply to 2018-02-14 10:11:23Z

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

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

This should work.

Stefan
3#
Stefan Reply to 2018-02-14 10:34:34Z

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 <%-.
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.367738 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO