module RWebLib
  module Core
    class Template
      def initialize(config)
        @config = config
      end

      def get_content(context, template_name)
        template_path = false
        subdir = context.eval('template_subdir')
        @config.page[:templates].each do |dir|
          path = dir
          path = File.expand_path(subdir, dir) if subdir
          path = File.expand_path(template_name + '.erb', path)
          template_path = path if File.file?(path) && File.readable?(path)
        end
        unless template_path
          raise TemplateError.new(
            "Cannot found template '#{template_name}' or this template is not readable."
          )
        end
        begin
          erb = ERB.new(File.read(template_path), 0, '<>')
          erb.filename = template_path
          erb.result(context)
        rescue StandardError => e
          raise TemplateError.new(e.message + " Templatefile: #{template_path}")
        end
      end
    end
  end
end
