问题
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
the puts
statement writes the output to the console. The docs for :ruby indicate that it
Creates an IO object named
haml_io
, anything written to it is output into the Haml document.
How exactly does one use the haml_io object to write to the haml document, but not to the console (think I need something other than puts
)?
回答1:
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
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
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.
回答2:
... Call puts on haml_io
?
Anything written to it is output into the Haml document.
回答3:
Note that if you are using https://github.com/k0kubun/hamlit as your renderer rather than plain https://github.com/haml/haml, the syntax for this is different again. It appears you just need to return the value you want from the filter.
None of the standard haml API's appear to work:
[46] pry(main)> Hamlit::Template.new() { ":ruby\n puts 'aaa'" }.render
aaa
=> ""
[47] pry(main)> Hamlit::Template.new() { ":ruby\n haml_io.puts 'aaa'" }.render
NameError: undefined local variable or method `haml_io' for #<Object:0x00007f9ec2f178a0>
from (__TEMPLATE__):1:in `__tilt_70159905806200'
[49] pry(main)> Hamlit::Template.new() { ":ruby\n 'aaa'" }.render
=> ""
But if you return from the :ruby
filter, you get the output:
[50] pry(main)> Hamlit::Template.new() { ":ruby\n return 'aaa'" }.render
=> "aaa"
I opened an issue about this, for reference: https://github.com/k0kubun/hamlit/issues/152
来源:https://stackoverflow.com/questions/17328758/output-haml-content-via-ruby-filter