erb 如何在数组上循环

erb how to loop on array

我不能简单地使用 ruby erb 模板系统在数组上循环...

这是我的模板:

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

这是命令行和结果

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

这个非常简单的例子有什么问题?

免责声明:我是 ruby erb 菜鸟 ^^

你不应该在末尾的“%”之前有那些“-”。

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

这应该有效。

您必须将 trim 模式 设置为 -:

$ erb -T - test.erb
foo
bar

来自手册页:

-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 <%-.