如何有条件地使用"content_for"哈姆包装纸

问题描述:

我正在尝试找到一种更干的方法来执行以下操作:

I am trying to find a more DRY way to do the following:

- if request.xhr?
  :javascript
    {my javascript}
- else
  = content_for :scripts do
    :javascript
      {my javascript}

我在许多Haml文件中重用了这种模式,所以我想知道什么是提取条件逻辑的最佳方法.理想情况下,我想在Haml文件中实现以下目标:

I reuse this pattern in many Haml files, so I am wondering what is the best way to abstract-out the conditional logic. Ideally, I'd like to achieve something like the following in my Haml files:

optional_content_for :scripts do
  :javascript
    {my javascript}

这似乎解决了我的需求,以防其他人有相同的请求...

This seems to solve my need, in case anyone else has the same request...

def script_content_for(&block)
  if request.xhr?
    capture_haml(&block)
  else
    content_for :scripts, nil, &block
  end
end

使用:

= script_content_for do
  :javascript
    {my js}