输出haml内容:ruby filter

当我使用:rubyfilter在haml中做一些简单的东西,例如…

 :ruby to = comments > max_comments ? max_comments : comments (0...to).each do |i| comment = data[i] puts li_comment comment[0], comment[1], comment[2] end 

puts语句将输出写入控制台。 文档:ruby表明它

创建一个名为haml_io的IO对象,写入它的任何内容都输出到Haml文档中。

究竟是如何使用 haml_io对象写入haml文档,而不是写入控制台(想想我需要除了puts之外的东西)?

最近这种行为发生了变化 – 旧行为(4.0版之前)是将写入标准的任何内容写入Haml文档,但这不是线程安全的。

haml_io是一个局部变量,它引用写入文档的IO对象 。 您重写的代码使用它看起来像这样(假设commentsmax_commentsli_comment都是先前定义的):

 :ruby to = comments > max_comments ? max_comments : comments (0...to).each do |i| comment = data[i] haml_io.puts li_comment comment[0], comment[1], comment[2] end 

haml_io实际上是一个StringIO对象,因此您可以使用它的任何方法,例如haml_io.writehaml_io.putc ,它会将输出重定向到您的文档。

…打电话给haml_io

写入的任何内容都输出到Haml文档中。