Ruby templates: How to pass variables into inlined ERB?

前端 未结 10 1724
陌清茗
陌清茗 2020-11-30 21:18

I have an ERB template inlined into Ruby code:

require \'erb\'

DATA = {
    :a => \"HELLO\",
    :b => \"WORLD\",
}

template = ERB.new <<-EOF
          


        
10条回答
  •  无人及你
    2020-11-30 22:08

    Got it!

    I create a bindings class

    class BindMe
        def initialize(key,val)
            @key=key
            @val=val
        end
        def get_binding
            return binding()
        end
    end
    

    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
    

    The .erb template file looks like this:

    Key: <%= @key %>
    

提交回复
热议问题