问题
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