|
| 1 | +require 'tilt' unless defined? Tilt |
| 2 | +require 'handlebars' |
| 3 | + |
| 4 | +module Tilt |
| 5 | + |
| 6 | + # Handlebars.rb template implementation. See: |
| 7 | + # https://github.com/cowboyd/handlebars.rb |
| 8 | + # and http://handlebarsjs.com |
| 9 | + # |
| 10 | + # Handlebars is a logic-less template rendered with JavaScript. |
| 11 | + # Handlebars.rb is a Ruby wrapper around Handlebars, that allows |
| 12 | + # Handlebars templates to be rendered server side. |
| 13 | + # |
| 14 | + class HandlebarsTemplate < Template |
| 15 | + def initialize_engine |
| 16 | + @context = ::Handlebars::Context.new |
| 17 | + end |
| 18 | + |
| 19 | + def self.engine_initialized? |
| 20 | + true |
| 21 | + end |
| 22 | + |
| 23 | + def prepare |
| 24 | + @context = ::Handlebars::Context.new |
| 25 | + @template = @context.compile(data) |
| 26 | + end |
| 27 | + |
| 28 | + def evaluate(scope, locals = {}, &block) |
| 29 | + # Based on LiquidTemplate |
| 30 | + locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h } |
| 31 | + if scope.respond_to?(:to_h) |
| 32 | + scope = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h } |
| 33 | + locals = scope.merge(locals) |
| 34 | + else |
| 35 | + scope.instance_variables.each do |var| |
| 36 | + key = var.to_s.delete("@") |
| 37 | + locals[key] = scope.instance_variable_get(var) unless locals.has_key? key |
| 38 | + end |
| 39 | + end |
| 40 | + |
| 41 | + locals['yield'] = block.nil? ? '' : yield |
| 42 | + locals['content'] = locals['yield'] |
| 43 | + |
| 44 | + @template.call(locals); |
| 45 | + end |
| 46 | + |
| 47 | + def register_helper(name, &fn) |
| 48 | + @context.register_helper(name, &fn) |
| 49 | + end |
| 50 | + |
| 51 | + def register_partial(*args) |
| 52 | + @context.register_partial(*args) |
| 53 | + end |
| 54 | + |
| 55 | + def partial_missing(&fn) |
| 56 | + @context.partial_missing(&fn) |
| 57 | + end |
| 58 | + |
| 59 | + def allows_script? |
| 60 | + false |
| 61 | + end |
| 62 | + end |
| 63 | + |
| 64 | + register HandlebarsTemplate, 'handlebars', 'hbs' |
| 65 | +end |
| 66 | + |
| 67 | + |
0 commit comments