Ruby模板:如何将变量传递给内联ERB? [英] Ruby templates: How to pass variables into inlined ERB?
本文介绍了Ruby模板:如何将变量传递给内联ERB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个内联到Ruby代码中的ERB模板:
I have an ERB template inlined into Ruby code:
require 'erb'
DATA = {
:a => "HELLO",
:b => "WORLD",
}
template = ERB.new <<-EOF
current key is: <%= current %>
current value is: <%= DATA[current] %>
EOF
DATA.keys.each do |current|
result = template.result
outputFile = File.new(current.to_s,File::CREAT|File::TRUNC|File::RDWR)
outputFile.write(result)
outputFile.close
end
我无法将变量 current传递给
I can't pass the variable "current" into the template.
错误是:
(erb):1: undefined local variable or method `current' for main:Object (NameError)
如何修复
推荐答案
知道了!
我创建了一个绑定类
class BindMe
def initialize(key,val)
@key=key
@val=val
end
def get_binding
return binding()
end
end
并将实例传递给ERB
and pass an instance to ERB
dataHash.keys.each do |current|
key = current.to_s
val = dataHash[key]
# here, I pass the bindings instance to ERB
bindMe = BindMe.new(key,val)
result = template.result(bindMe.get_binding)
# unnecessary code goes here
end
.erb模板文件如下:
The .erb template file looks like this:
Key: <%= @key %>
这篇关于Ruby模板:如何将变量传递给内联ERB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文