Home > Net >  Unexpected `;` when trying to trim extra endlines
Unexpected `;` when trying to trim extra endlines

Time:06-29

I'm learning how to use erb (and ruby for that matter) and having a hard time replicating examples from this site where the authors demonstrate that you can remove the trailing endline by closing a block with -%> but when I do this I get a syntax error

syntax error, unexpected ';' (Syntax Error); @values.each do |val| -; _erbout.<< "\\n".freeze

Here's an example of my code that doesn't run

<% @values = ['one','two']; puts "Was assigned."%>
<% @values.each do |val| -%>
Some stuff with <%= val %>
<% end -%>

But the following runs

<% @values = ['one','two']; puts "Was assigned."%>
<% @values.each do |val| %>
Some stuff with <%= val %>
<% end %>

Final Solution

Just to add to the accepted answer, I was running erb from the command line with

erb test.cfg.erb

Reading man erb you can enable newline trimming by setting -T with the option - so

erb -T - test.cfg.erb

Is the command I was looking for.

CodePudding user response:

If you check out the ERB class doc, you'll see there's an optional trim_mode keyword argument in ERB.new, and one of its possible values is:

-  omit blank lines ending in -%>

By default, the -%> elements are just considered invalid.

Now if you compile your first template giving it the correct trim_mode option:

str = %q(
<% @values = ['one','two']; puts "Was assigned."%>
<% @values.each do |val| -%>
Some stuff with <%= val %>
<% end -%>
)

erb = ERB.new(str, trim_mode: '-')  # Without trim_mode you'll get the error
puts erb.result(binding)

You'll get the correct result:

Was assigned.


Some stuff with one
Some stuff with two

The guide you've linked to is from Puppet, and presumably they use ERB internally for templating and always pass it the trim_mode: '-' option. But if you're using ERB directly, you have to remember to include it yourself.

  • Related