Ruby ERB 渲染和定义函数
Ruby ERB render and def function
我在使用 ERB 进行实验时遇到了一个奇怪的问题。我这里有什么代码:
# cat ./services_lbs2.erb
<%= def renderVip(description, template)
puts "zxc dfg"
end
%>
# locally and remote
Printing: <%= renderVip('123','456') %>
这是我在 irb 中得到的:
irb(main):034:0> @template=File.read('./services_lbs2.erb')
=> "<%= def renderVip(description, template)\nputs \"zxc dfg\"\nend\n%>\n# locally and remotely monitored (all externals)\nPrinting: <%= renderVip('123','456') %>\n"
irb(main):035:0> zxc = ERB.new(@template,nil, "-")
=> #<ERB:0x00000000068d4d88 @safe_level=nil, @src="#coding:US-ASCII\n_erbout = String.new; _erbout.concat(( def renderVip(description, template)\nputs \"zxc dfg\"\nend\n).to_s); _erbout.concat \"\n# locally and remotely monitored (all externals)\nPrinting: \"\n\n; _erbout.concat(( renderVip('123','456') ).to_s); _erbout.concat \"\n\"\n; _erbout.force_encoding(__ENCODING__)", @encoding=#<Encoding:US-ASCII>, @frozen_string=nil, @filename=nil, @lineno=0>
irb(main):036:0> zxc.result(binding)
zxc dfg
=> "renderVip\n# locally and remotely monitored (all externals)\nPrinting: \n"
我无法得到如下输出:
# locally and remotely monitored (all externals)\nPrinting: zxc dfg\n
为什么会这样,如何解决?
谢谢!
return 值 puts
函数是 nil
因此在您的情况下,该方法将 return nil
.
所以执行后 nil
被附加到 body
标签内。为此,将其更改为
<%
def renderVip(description, template)
"zxc dfg"
end
%>
我在使用 ERB 进行实验时遇到了一个奇怪的问题。我这里有什么代码:
# cat ./services_lbs2.erb
<%= def renderVip(description, template)
puts "zxc dfg"
end
%>
# locally and remote
Printing: <%= renderVip('123','456') %>
这是我在 irb 中得到的:
irb(main):034:0> @template=File.read('./services_lbs2.erb')
=> "<%= def renderVip(description, template)\nputs \"zxc dfg\"\nend\n%>\n# locally and remotely monitored (all externals)\nPrinting: <%= renderVip('123','456') %>\n"
irb(main):035:0> zxc = ERB.new(@template,nil, "-")
=> #<ERB:0x00000000068d4d88 @safe_level=nil, @src="#coding:US-ASCII\n_erbout = String.new; _erbout.concat(( def renderVip(description, template)\nputs \"zxc dfg\"\nend\n).to_s); _erbout.concat \"\n# locally and remotely monitored (all externals)\nPrinting: \"\n\n; _erbout.concat(( renderVip('123','456') ).to_s); _erbout.concat \"\n\"\n; _erbout.force_encoding(__ENCODING__)", @encoding=#<Encoding:US-ASCII>, @frozen_string=nil, @filename=nil, @lineno=0>
irb(main):036:0> zxc.result(binding)
zxc dfg
=> "renderVip\n# locally and remotely monitored (all externals)\nPrinting: \n"
我无法得到如下输出:
# locally and remotely monitored (all externals)\nPrinting: zxc dfg\n
为什么会这样,如何解决?
谢谢!
return 值 puts
函数是 nil
因此在您的情况下,该方法将 return nil
.
所以执行后 nil
被附加到 body
标签内。为此,将其更改为
<%
def renderVip(description, template)
"zxc dfg"
end
%>