Ruby 模板:如何将变量传递给内联 ERB? [英] Ruby templates: How to pass variables into inlined ERB?

查看:26
本文介绍了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 %>

这篇关于Ruby 模板:如何将变量传递给内联 ERB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆