liquid.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. require 'tilt/template'
  2. module Tilt
  3. # Liquid template implementation. See:
  4. # http://liquid.rubyforge.org/
  5. #
  6. # Liquid is designed to be a *safe* template system and threfore
  7. # does not provide direct access to execuatable scopes. In order to
  8. # support a +scope+, the +scope+ must be able to represent itself
  9. # as a hash by responding to #to_h. If the +scope+ does not respond
  10. # to #to_h it will be ignored.
  11. #
  12. # LiquidTemplate does not support yield blocks.
  13. #
  14. # It's suggested that your program require 'liquid' at load
  15. # time when using this template engine.
  16. class LiquidTemplate < Template
  17. def self.engine_initialized?
  18. defined? ::Liquid::Template
  19. end
  20. def initialize_engine
  21. require_template_library 'liquid'
  22. end
  23. def prepare
  24. @engine = ::Liquid::Template.parse(data)
  25. end
  26. def evaluate(scope, locals, &block)
  27. locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
  28. if scope.respond_to?(:to_h)
  29. scope = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
  30. locals = scope.merge(locals)
  31. end
  32. locals['yield'] = block.nil? ? '' : yield
  33. locals['content'] = locals['yield']
  34. @engine.render(locals)
  35. end
  36. end
  37. end