【问题标题】:Nested capture_haml helpers嵌套的 capture_haml 助手
【发布时间】:2014-07-27 20:50:01
【问题描述】:

我有以下两个辅助方法:

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_world 中致电hello。我单独尝试了hellocapture_haml hellohaml_tag hello,还结合了.html_safe,但没有任何解决方案能够奏效。

我该怎么做?

我真的更愿意直接使用capture_haml 而不是haml_tag,因为我认为在视图中

= hello_world

干净得多
- hello_world

谢谢

【问题讨论】:

  • 您在World 之后缺少' — 这只是一个错字吗?
  • 是的,这只是一个错字。 :)

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


【解决方案1】:

你的hello 方法,因为它使用capture_haml 只是返回一个字符串。当你在hello_world 方法的capture_haml 块内调用它时,它什么也不做——创建并返回一个字符串,但你根本不使用它。因为它没有被写入输出,所以它没有被capture_haml 捕获。

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

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

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

【讨论】:

  • 感谢您的详细解答。这正是我所困惑的!
  • 你提到的haml_concat 让我从另一个小时的困惑中解脱出来,谢谢!!
【解决方案2】:

找到了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    相关资源
    最近更新 更多