在ERB模板中转义行返回/结束行

Tec*_*Zen 6 ruby formatting erb macruby

我需要能够在ERB中格式化未打印的逻辑行,而不会影响模板的最终文本输出.在这一点上,我认为ERB不支持这种逃避.

这是我的第一个主要Ruby项目.我正在编写代码生成器.我的模板将包含大量的条件和枚举.为了使模板可读和可维护,我需要能够格式化逻辑代码和注释,而不会扭曲最终输出.

例如假设我想要这个输出:

Starting erbOutput
1
2
3
4
Ending erbOutput
Run Code Online (Sandbox Code Playgroud)

我天真地写了这样的模板:

require 'erb'
h=<<H
Starting erbOutput
<%# comment %>
<%5.times do |e|%>
<%=e.to_s  %>
<%end %>
<%# comment %>
Ending erbOutput
H
s=ERB.new(h).result
puts s
Run Code Online (Sandbox Code Playgroud)

......但这会产生

Starting erbOutput


0

1

2

3

4


Ending erbOutput
Run Code Online (Sandbox Code Playgroud)

直印:

"Starting erbOutput\n\n\n0\n\n1\n\n2\n\n3\n\n4\n\n\nEnding erbOutput\n"
Run Code Online (Sandbox Code Playgroud)

...清楚地表明逻辑和注释行的换行符包含在ERB输出中.

我可以通过将模板塞入这种笨拙的形式来产生所需的输出:

h=<<H
Starting erbOutput<%# comment %>
<%5.times do |e|%><%=e.to_s  %>
<%end %><%# comment %>Ending erbOutput
H
Run Code Online (Sandbox Code Playgroud)

...但我不认为我可以在没有更多可读格式的情况下调试和维护模板.我的一些条件和枚举深达三个级别,我评论很多.在一行或两行上填写所有内容会使模板完全无法读取.

有没有办法逃避或以其他方式抑制ERB中注释行的逻辑行返回?其他常用的Ruby模板模块是否能更好地处理这个问题?

如果它很重要,我在MacOS 10.6.7上使用MacRuby 0.10(实现Ruby 1.9.2).

saw*_*awa 3

正如 Rom1 和 Kyle 所建议的,您可以将参数传递给ERB.new,但是这样,您将不会在您想要的位置得到换行符。

require 'erb'
h=<<H
Starting erbOutput
<%# comment %>
<%5.times do |e|%>
<%=e.to_s  %>
<%end %>
<%# comment %>
Ending erbOutput
H
s=ERB.new(h, nil, '<>').result
puts s
Run Code Online (Sandbox Code Playgroud)

给你

Starting erbOutput
01234Ending erbOutput
Run Code Online (Sandbox Code Playgroud)

所以你需要显式插入额外的行

require 'erb'
h=<<H
Starting erbOutput
<%# comment %>
<%5.times do |e|%>
<%=e.to_s  %>

<%end %>
<%# comment %>
Ending erbOutput
H
s=ERB.new(h, nil, '<>').result
puts s
Run Code Online (Sandbox Code Playgroud)

这将给出:

Starting erbOutput
0
1
2
3
4
Ending erbOutput
Run Code Online (Sandbox Code Playgroud)