Sha256: 7e9d16ea50171012550cd254d2d391368c5a23442bbb9c8ac9061f4ba690a966

Contents?: true

Size: 1.51 KB

Versions: 1

Compression:

Stored size: 1.51 KB

Contents

require 'tilt'
class Rack::App::FrontEnd::Template

  require 'rack/app/front_end/template/scope'
  require 'rack/app/front_end/template/default_layout'
  require 'rack/app/front_end/template/default_template'

  def self.cache
    @cache ||= Tilt::Cache.new
  end

  def self.template?(file_path)
    not Tilt.templates_for(file_path).empty?
  end

  def render(current_scope, variables={}, &block)
    scope = create_scope(current_scope)

    layout.render(scope, variables) { template.render(scope, variables, &block) }
  end

  protected

  DEFAULT_TEMPLATE_OPTIONS = {:default_encoding => "utf-8"}

  def initialize(template_path, options={})
    @file_path = template_path
    @layout_path = options.delete(:layout_path)
    @template_options = DEFAULT_TEMPLATE_OPTIONS.merge(options)
  end

  def template
    if self.class.template?(@file_path)
      get_template(@file_path)
    else
      DefaultTemplate.new(@file_path)
    end
  end

  def layout
    return DefaultLayout if use_default_layout?

    get_template(@layout_path)
  end

  def use_default_layout?
    @layout_path.nil? or
        not File.exist?(@layout_path) or
        (@file_path =~ /^#{Regexp.escape(Rack::App::Utils.namespace_folder(@layout_path))}/)
  end

  def get_template(file_path)
    self.class.cache.fetch(file_path) { Tilt.new(file_path, @template_options) }
  end

  def create_scope(current_scope)
    new_scope = Scope.new
    new_scope.inherit_instance_variables!(current_scope)
    new_scope.inherit_modules!(current_scope)
    new_scope
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rack-app-front_end-0.15.0 lib/rack/app/front_end/template.rb