繁体   English   中英

如何在Rails视图中干燥条件content_for?

[英]How can I DRY up conditional content_for in Rails view?

比赛/ show.html.haml:

- if modal
  - content_for(:modal_header) do
    = render 'contests/contest_header'
  - content_for(:modal_body) do
    = render 'contests/contest_body'
- else
  = render 'contests/contest_header'
  = render 'contests/contest_body'

modal是一个布尔型局部变量,它指示视图是在模式模板中呈现的,还是在常规应用程序模板中呈现的。 模态具有content_for块,而主应用程序模板则没有:

布局/ modal.html.haml:

-modal = true
.modal-header
  .row
    .col-xs-11
      = yield(:modal_header)
    .col-xs-1
      %button{'type': 'button', 'class': 'close', 'data-dismiss': 'modal', 'aria-label': 'close'}
        %span{'aria-hidden': 'true'} ×
.modal-body
  = render 'layouts/messages'
  - if content_for?(:modal_body)
    = yield(:modal_body)
  - else
    =yield

我正在寻找的是可以在modal为false时有条件地禁用content_for块的东西。 而不是重复我的渲染语句。

从另一个SO答案中找到了解决方案! https://stackoverflow.com/a/27398070/378622

这是我的实现

# app/helpers/application_helper.rb
def modal_content_for(name, &block)
  if params[:modal] == '1'
    content_for 'modal_' + name.to_s, nil, &block
  else
    capture_haml(&block)
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM