关于使用“打印”方法在 ERB 中进行元编程等
我通过控制台使用 ERB 进行元编程(用于数学软件)。例如,我有文件 test.erb
包含
text line before ruby
<%= 'via <%=' %>
<% print 'print' %>
<% puts 'puts' %>
text line after ruby
当我通过 $ erb test.erb
解析它时,我得到以下输出
printputs
text line before ruby
via <%=
text line after ruby
我对此并不感到惊讶,但想知道是否有没有一种好方法可以捕获 print
方法的输出并将其放在 ERB 模板中调用它的位置?
text line before ruby
via <%=
print
puts
text line after ruby
想象一下,我有一个复杂的结构,我更愿意打印而不是在 <%= %>
内的字符串中收集输出。
更新
只是为了说明Brian的答案:
text line before ruby
<%= '<%=' %>
% print 'print'
% puts 'puts'
% E = _erbout
% E << '_erbout'+"\n"
text line after ruby
解析文件$ erb test.erb
:
printputs
text line before ruby
<%=
_erbout
text line after ruby
I am using ERB via console for metaprogramming (for math software). For example, I have file test.erb
containing
text line before ruby
<%= 'via <%=' %>
<% print 'print' %>
<% puts 'puts' %>
text line after ruby
When I parse it by $ erb test.erb
, I get the following output
printputs
text line before ruby
via <%=
text line after ruby
I am not surprised by it, but wonder if there is a good way to catch output of print
method and put it at the place where it is called in the ERB template?
text line before ruby
via <%=
print
puts
text line after ruby
Imagine that I have a complex construction, where I would prefer to print instead of collecting output in a string inside <%= %>
.
Update
Just to illustrate the answer of Brian:
text line before ruby
<%= '<%=' %>
% print 'print'
% puts 'puts'
% E = _erbout
% E << '_erbout'+"\n"
text line after ruby
Parsing the file $ erb test.erb
:
printputs
text line before ruby
<%=
_erbout
text line after ruby
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定这是否对您的特定情况有帮助,但请考虑使用 _erbout 方法查看一些示例,
希望这能让您有所收获。
Not certain if this helps in your particular case, but consider looking at some examples using the _erbout method
Hope this gets you somewhere.
作为一种选择,可以重新定义
Kernel#p
方法:file: p_for_erb.rb
...然后执行类似的操作:
file: mytest.erb
Command
$ erb mytest.erb产生
As an option, one can redefine
Kernel#p
method:file: p_for_erb.rb
...and then do similar to this:
file: mytest.erb
Command
$ erb mytest.erb
produces