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)
我该如何解决这个问题?
How do I fix this?
答
知道了!
我创建了一个绑定类
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 %>