生成带有重用参数的Ruby ERB模板

时间:2018-04-16 18:38:02

标签: ruby erb reusability

从ERB创建一个html模板。我可以通过分别添加页眉,页脚和正文来生成模板。正文中的内容包含嵌入的ruby代码,该代码在ERB对象和绑定上下文期间进行评估。我希望将哈希参数传递给正文,并使用ruby代码进行迭代以进行评估。我已尝试使用openStruct将散列作为参数发送,但散列中的键表现为对象方法(hash。{key})而不再是键值对。

github_gist

## Generates an html page using ERB
    require 'erb'

    *Initializes the key,val objects to bind the erb templates
    class BindMe
      attr_accessor :key
      attr_accessor :val

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

    * hash parameter
    items = {'A' => 1, 'B' =>  2, 'C' => 3}
    arr= []
    * Generating objects to bind each object with ERB template
    items.each do |key,value|
      #binding.pry
      bind_me = BindMe.new(key.to_s,value)
      arr.push(bind_me)
    end
    * Template to be used
    template = '''
    <html>
      <head>
      </head>
      <body>
        <table>
          <tr>
            <td> <h1>  KEY  </h1> </td>
            <td> <h1> VALUE </h1> </td>
          </tr>
          <tr>
            <td> <h3> Name:<%= key %> </h3> </td>
            <td> <h3> value: <%= val %> </h3> </td>
          </tr>
        </table>
      </body>
    </html>
    '''
    puts arr

    * loops in on the array objects 
      Here it would be useful to pass the arr objects as params with ERB 
      to template and use ruby code in template to loop in and gen. 
      complete  html in one call


    arr.each do |ele|
      #binding.pry
      result = ERB.new(template).result(ele.get_binding)
      puts result
      open('index2.html', 'w+') { |f|
        f.puts result
      }
    end

0 个答案:

没有答案