3

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

nemenems
  • 1,064
  • 2
  • 9
  • 27

2 Answers2

5

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

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

This should work.

Oli Crt
  • 1,123
  • 1
  • 11
  • 13
  • 1
    indeed it works! but I don't understand, the "-"is here to not add a newline char (from my understanding). I saw a lot of examples with this syntax. Why am i not supposed to use the "-" here ? – nemenems Feb 14 '18 at 10:16
  • @nemenems Seems like you need to enable it doing `ERB.new(template, nil, '-')`, see this post for more info https://stackoverflow.com/questions/4632879/erb-template-removing-the-trailing-line – Oli Crt Feb 14 '18 at 10:22
  • 1
    perfect! you rocks! – nemenems Feb 14 '18 at 11:02
3

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 <%-.
Stefan
  • 109,145
  • 14
  • 143
  • 218