deruse
deruse

Reputation: 2881

How to conditionally use a "content_for" wrapper in Haml

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}

Upvotes: 0

Views: 376

Answers (1)

deruse
deruse

Reputation: 2881

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}

Upvotes: 1

Related Questions