class Tilt::HandlebarsTemplate

Handlebars.rb template implementation. See: github.com/cowboyd/handlebars.rb and handlebarsjs.com

Handlebars is a logic-less template rendered with JavaScript. Handlebars.rb is a Ruby wrapper around Handlebars, that allows Handlebars templates to be rendered server side.

Public Instance Methods

allows_script?() click to toggle source
# File lib/tilt/handlebars.rb, line 59
def allows_script?
  false
end
evaluate(scope, locals = {}) { || ... } click to toggle source
# File lib/tilt/handlebars.rb, line 28
def evaluate(scope, locals = {}, &block)
  # Based on LiquidTemplate
  locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
  if scope.respond_to?(:to_h)
    scope  = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
    locals = scope.merge(locals)
  else
    scope.instance_variables.each do |var|
      key = var.to_s.delete("@")
      locals[key] = scope.instance_variable_get(var) unless locals.has_key? key
    end
  end

  locals['yield'] = block.nil? ? '' : yield
  locals['content'] = locals['yield']

  @template.call(locals);
end
initialize_engine() click to toggle source
# File lib/tilt/handlebars.rb, line 16
def initialize_engine
  return if defined? ::Handlebars
  require_template_library 'handlebars'
end
partial_missing(&fn) click to toggle source
# File lib/tilt/handlebars.rb, line 55
def partial_missing(&fn)
  @context.partial_missing(&fn)
end
prepare() click to toggle source
# File lib/tilt/handlebars.rb, line 21
def prepare
  @context = ::Handlebars::Context.new
  @context.partial_missing { |partial_name| load_partial partial_name }
  @template = @context.compile(data)
end
register_helper(name, &fn) click to toggle source
# File lib/tilt/handlebars.rb, line 47
def register_helper(name, &fn)
  @context.register_helper(name, &fn)
end
register_partial(*args) click to toggle source
# File lib/tilt/handlebars.rb, line 51
def register_partial(*args)
  @context.register_partial(*args)
end

Private Instance Methods

load_partial(partial_name) click to toggle source
# File lib/tilt/handlebars.rb, line 63
def load_partial(partial_name)
  if Pathname.new(partial_name).absolute? 
    dir = ""
  elsif file
    dir = File.dirname file
  end

  partial_file = File.expand_path("#{partial_name}.hbs", dir)
  partial_file = File.expand_path("#{partial_name}.handlebars", dir) unless File.file? partial_file
  if File.file? partial_file
    return IO.read(partial_file)
  end

  raise "The partial '#{partial_name}' could not be found. No such file #{partial_file}"
end