如何将yml文件的内容传递给我的erb模板?

时间:2012-11-17 17:33:26

标签: ruby yaml erb

我的yml文件如下:

defaults: &defaults
  key1: value1
  key2: value2
  ..
  ..

我的模板文件包含以下内容:

<%= key1 %>
<%= key2 %>

所以我的脚本有一个文件列表,循环遍历它们,我想将yml对象传递给我的erb进行解析:

config = YAML::load(File.open('config.yml'))ENV['ENV']

file_names.each do |fn|

  file = File.new "#{fn}", "r"

  template = ERB.new file

  result = template.result

  # save file here

end

如何将配置对象传递给erb模板系统?

1 个答案:

答案 0 :(得分:4)

http://ciaranm.wordpress.com/2009/03/31/feeding-erb-useful-variables-a-horrible-hack-involving-bindings/

的帮助下

不是很漂亮,但是如果你把课程藏起来那么它就不那么糟糕了。下面是你可能会遇到调用ThingsForERB类中不存在的其他方法的问题,因此在改变事情之前你需要考虑这个问题,以便像Sergio建议的那样使用config['key1']

require 'erb'

config = {'key1' => 'aaa', 'key2' => 'bbb'}

class ThingsForERB
  def initialize(hash)
    @hash = hash.dup
  end
  def method_missing(meth, *args, &block)
    @hash[meth.to_s]
  end
  def get_binding
    binding
  end
end


template = ERB.new <<-EOF
  The value of key1 is: <%= key1 %>
  The value of key2 is: <%= key2 %>
EOF
puts template.result(ThingsForERB.new(config).get_binding)

运行时输出为:

  The value of key1 is: aaa
  The value of key2 is: bbb