2012-03-22 39 views
5

Tôi có kịch bản Ruby sau:Blocks trong ERB tinh khiết/Erubis

require 'erubis' 

def listing(title, attributes={}) 
    "output" + yield + "more output" 
end 

example = %Q{<% listing "db/migrate/[date]_create_purchases.rb", :id => "ch01_292" do %> 
<![CDATA[class CreatePurchases < ActiveRecord::Migration 
    def change 
    create_table :purchases do |t| 
     t.string :name 
     t.float :cost 
     t.timestamps 
    end 
    end 
end]]> 
<% end %>} 

chapter = Erubis::Eruby.new(example) 
p chapter.result(binding) 

Tôi đang cố gắng sử dụng một khối ở đây và làm cho nó ra "đầu ra", sau đó các nội dung trong khối và sau đó "hơn đầu ra ", nhưng tôi dường như không thể làm cho nó hoạt động.

Tôi biết rằng ERB được sử dụng để làm việc theo cách này trong Rails 2.3 và bây giờ làm việc với <%= trong Rails 3 ... nhưng tôi không sử dụng Rails cả. Đây chỉ là ERB thuần túy.

Làm cách nào để có thể xuất tất cả nội dung?

Trả lời

3

Jeremy McAnally liên kết tôi với this perfect description cách thực hiện.

Về cơ bản, bạn cần báo cho ERB lưu bộ đệm đầu ra trong một biến.

Các kịch bản kết thúc lên tim như thế này:

require 'erb' 

def listing(title, attributes={}) 
    concat %Q{ 
<example id='#{attributes[:id]}'> 
    <programlisting> 
    <title>#{title}</title>} 
    yield 
    concat %Q{ 
    </programlisting> 
</example> 
    } 
end 

def concat(string) 
    @output.concat(string) 
end 

example = %Q{<% listing "db/migrate/[date]_create_purchases.rb", :id => "ch01_292" do %> 
<![CDATA[class CreatePurchases < ActiveRecord::Migration 
    def change 
    create_table :purchases do |t| 
     t.string :name 
     t.float :cost 
     t.timestamps 
    end 
    end 
end]]> 
<% end %>} 

chapter = ERB.new(example, nil, nil, "@output") 
p chapter.result(binding) 
0

vĩ đại. Tôi nhớ đã nhìn thấy điều đó một lúc trước. Chơi một chút, tôi đã nhận được điều này:

require 'erubis' 

def listing(title, attributes={}) 
    %Q{<%= "output #{yield} more output" %>} 
end 

example = listing "some title", :id => 50 do 
      def say_something 
       "success?" 
      end 
      say_something 
      end 


c = Erubis::Eruby.new(example) 
p c.evaluate 
# => "output success? more output" 
Các vấn đề liên quan