嵌套的capture_haml助手

时间:2014-07-27 20:50:02

标签: ruby-on-rails-3 haml helper

我有以下两种辅助方法:

def hello
  capture_haml do
    haml_tag :div, 'Hello'
  end
end

def hello_world
  capture_haml do
    hello # How can I call it here?
    haml_tag :div, 'World'
  end
end

我想在hello中致电hello_world。我单独尝试了hellocapture_haml hellohaml_tag hello,并结合了.html_safe,但没有任何解决方案可行。

我该怎么做?

我宁愿直接使用capture_haml而不是haml_tag因为我认为在视图中

= hello_world

更清洁
- hello_world

由于

2 个答案:

答案 0 :(得分:1)

您的hello方法,因为它使用capture_haml只返回一个字符串。当你在capture_haml方法中的hello_world块内调用它时它没有做任何事情 - 创建并返回一个字符串,但你根本不使用它。由于它未写入输出,因此capture_haml不会捕获它。

您可以使用haml_concat将字符串写入输出,这将强制capture_haml起作用,如下所示:

def hello_world
  capture_haml do
    haml_concat hello
    haml_tag :div, 'World'
  end
end

这是一个非常人为的例子,但我希望它能说明发生了什么。 capture_haml获取一个通常直接写入输出的块(通常是Haml源)并将其作为字符串返回。 haml_concat接受一个字符串并将其写入输出,因此在某些方面与capture_haml相反。

答案 1 :(得分:0)

找到它:

def hello
  capture_haml do
    haml_tag :div, 'Hello'
  end
end

def hello_world
  capture_haml do
    haml_tag :div, hello
    haml_tag :div, 'World'
  end
end