Permalink
Browse files

adding nokogiri template support

  • Loading branch information...
1 parent addb4a1 commit d2e2601ad89ae139c702a15231ecd8e413407f37 @tenderlove tenderlove committed Jul 29, 2010
Showing with 81 additions and 0 deletions.
  1. +27 −0 lib/tilt.rb
  2. +54 −0 test/tilt_nokogiritemplate_test.rb
View
@@ -555,6 +555,33 @@ def evaluate(scope, locals, &block)
register 'less', LessTemplate
+ # Nokogiri template implementation. See:
+ # http://nokogiri.org/
+ class NokogiriTemplate < Template
+ def initialize_engine
+ return if defined?(::Nokogiri)
+ require_template_library 'nokogiri'
+ end
+
+ def prepare; end
+
+ def evaluate(scope, locals, &block)
+ xml = ::Nokogiri::XML::Builder.new
+ if data.respond_to?(:to_str)
+ locals[:xml] = xml
+ super(scope, locals, &block)
+ elsif data.kind_of?(Proc)
+ data.call(xml)
+ end
+ xml.to_xml
+ end
+
+ def precompiled_template(locals)
+ data.to_str
+ end
+ end
+ register 'nokogiri', NokogiriTemplate
+
# Builder template implementation. See:
# http://builder.rubyforge.org/
class BuilderTemplate < Template
@@ -0,0 +1,54 @@
+require 'contest'
+require 'tilt'
+
+begin
+ require 'nokogiri'
+ class NokogiriTemplateTest < Test::Unit::TestCase
+ test "registered for '.nokogiri' files" do
+ assert_equal Tilt::NokogiriTemplate, Tilt['test.nokogiri']
+ assert_equal Tilt::NokogiriTemplate, Tilt['test.xml.nokogiri']
+ end
+
+ test "preparing and evaluating the template on #render" do
+ template = Tilt::NokogiriTemplate.new { |t| "xml.em 'Hello World!'" }
+ doc = Nokogiri.XML template.render
+ assert_equal 'Hello World!', doc.root.text
+ assert_equal 'em', doc.root.name
+ end
+
+ test "passing locals" do
+ template = Tilt::NokogiriTemplate.new { "xml.em('Hey ' + name + '!')" }
+ doc = Nokogiri.XML template.render(Object.new, :name => 'Joe')
+ assert_equal 'Hey Joe!', doc.root.text
+ assert_equal 'em', doc.root.name
+ end
+
+ test "evaluating in an object scope" do
+ template = Tilt::NokogiriTemplate.new { "xml.em('Hey ' + @name + '!')" }
+ scope = Object.new
+ scope.instance_variable_set :@name, 'Joe'
+ doc = Nokogiri.XML template.render(scope)
+ assert_equal 'Hey Joe!', doc.root.text
+ assert_equal 'em', doc.root.name
+ end
+
+ test "passing a block for yield" do
+ template = Tilt::NokogiriTemplate.new { "xml.em('Hey ' + yield + '!')" }
+ doc = Nokogiri.XML template.render { 'Joe' }
+ assert_equal 'Hey Joe!', doc.root.text
+ assert_equal 'em', doc.root.name
+ end
+
+ test "block style templates" do
+ template =
+ Tilt::NokogiriTemplate.new do |t|
+ lambda { |xml| xml.em('Hey Joe!') }
+ end
+ doc = Nokogiri.XML template.render template.render
+ assert_equal 'Hey Joe!', doc.root.text
+ assert_equal 'em', doc.root.name
+ end
+ end
+rescue LoadError
+ warn "Tilt::NokogiriTemplate (disabled)"
+end

0 comments on commit d2e2601

Please sign in to comment.