4

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

1
  • 1
    The thing that error message is also pretty unclear. To me, it should have told you unexpected '-' Commented Oct 7, 2019 at 16:01

2 Answers 2

6

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

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

This should work.

Sign up to request clarification or add additional context in comments.

3 Comments

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 Seems like you need to enable it doing ERB.new(template, nil, '-'), see this post for more info stackoverflow.com/questions/4632879/…
perfect! you rocks!
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 <%-.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.