通过:ruby过滤器输出haml内容 [英] Output haml content via :ruby filter

查看:82
本文介绍了通过:ruby过滤器输出haml内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,当我使用:ruby过滤器在haml中做一些简单的事情时,...

When I use the :ruby filter to do some simple stuff in haml, for example...

: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语句将输出写入控制台. 文档

the puts statement writes the output to the console. The docs for :ruby indicate that it

创建一个名为haml_io的IO对象,写入其中的所有内容都会输出 进入Haml文档.

Creates an IO object named haml_io, anything written to it is output into the Haml document.

如何精确地使用haml_io对象将haml_io对象写入haml文档,而不是写入控制台(认为我需要puts以外的东西)?

推荐答案

此行为最近已更改 –以前的行为(在4.0版之前)是将任何以标准方式写的东西写到Haml文档中,但这不是线程安全的.

This behaviour changed recently – the old behaviour (before version 4.0) was to write anything written to standard out to the Haml document, but this wasn’t thread safe.

haml_io局部变量,是指写入文档的IO对象.重写为使用它的代码将类似于以下内容(假设commentsmax_commentsli_comment均已在前面定义):

haml_io is a local variable that refers to an IO object that writes to the document. Your code rewritten to use it would look something like this (assuming comments, max_comments and li_comment are all defined earlier):

: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 is actually a StringIO object so you can use any of its methods, e.g. haml_io.write, haml_io.putc and it will redirect output to your document.

这篇关于通过:ruby过滤器输出haml内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆