Conditionally use a content_for wrapper in haml

非 Y 不嫁゛ 提交于 2020-01-17 03:55:53

问题


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}

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}

Thanks!


回答1:


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

Use:

= script_content_for do
  :javascript
    {my js}


来源:https://stackoverflow.com/questions/27397560/conditionally-use-a-content-for-wrapper-in-haml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!