Sha256: c74ab75114a73010374450ca0dfc68658b190f846b6851ed8dd0766d8589b0e4

Contents?: true

Size: 1.5 KB

Versions: 10

Compression:

Stored size: 1.5 KB

Contents

module Sablon
  class Template
    def initialize(path)
      @path = path
    end

    # Same as +render_to_string+ but writes the processed template to +output_path+.
    def render_to_file(output_path, context, properties = {})
      File.open(output_path, 'wb') do |f|
        f.write render_to_string(context, properties)
      end
    end

    # Process the template. The +context+ hash will be available in the template.
    def render_to_string(context, properties = {})
      render(context, properties).string
    end

    private
    def render(context, properties = {})
      Zip::OutputStream.write_buffer(StringIO.new) do |out|
        Zip::File.open(@path).each do |entry|
          entry_name = entry.name
          out.put_next_entry(entry_name)
          content = entry.get_input_stream.read
          if entry_name == 'word/document.xml'
            out.write(process(content, context, properties))
          elsif entry_name =~ /word\/header\d*\.xml/ || entry_name =~ /word\/footer\d*\.xml/
            out.write(process(content, context))
          else
            out.write(content)
          end
        end
      end
    end

    # process the sablon xml template with the given +context+.
    #
    # IMPORTANT: Open Office does not ignore whitespace around tags.
    # We need to render the xml without indent and whitespace.
    def process(content, context, *args)
      document = Nokogiri::XML(content)
      Processor.process(document, context, *args).to_xml(indent: 0, save_with: 0)
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
sablon-0.0.18 lib/sablon/template.rb
sablon-0.0.17 lib/sablon/template.rb
sablon-0.0.16 lib/sablon/template.rb
sablon-0.0.15 lib/sablon/template.rb
sablon-0.0.14 lib/sablon/template.rb
sablon-0.0.13 lib/sablon/template.rb
sablon-0.0.12 lib/sablon/template.rb
sablon-0.0.11 lib/sablon/template.rb
sablon-0.0.10 lib/sablon/template.rb
sablon-0.0.9 lib/sablon/template.rb