Rails: Refactoring HTML producing helper method to use a partial - how to use blocks there?

こ雲淡風輕ζ 提交于 2020-01-03 05:28:30

问题


After my earlier question Developing helper functions that generate HTML: should I rather use nested content_tag()s or partials? I am convinced now to rewrite some of my more complex HTML generating helper functions to use templates instead of nested content_tag() calls.

So here's my original helper:

def bootstrap_navlist(&block)
  classes = ['nav', 'nav-list']

  content_tag(:ul, class: classes.join(' ')) do
    capture(self, &block)
  end
end

And that's what I came up with using a partial now:

def bootstrap_navlist(&block)
  render partial: 'bootstrap/navlist'
end

# views/bootstrap/_navlist.html.erb
<ul class="<%= ['nav', 'nav-list'].join(' ') %>">
  How do I output the block here??
</ul>

The block looks something like this, but it can be any HTML you like:

= bootstrap_navlist do |navlist|
  = navlist.item 'Home', '#'
  = navlist.sublist 'Meine Favoriten', '/favorites' do |sublist|

As you can guess, I'm not sure how to output the block in the view. Should I simply capture it in the helper and pass it as a :local variable? Or is there a more common way?

Thanks a lot.


回答1:


This is a case where the content tags were not deeply nested an would be reasonable as a helper.

Your helper, and partial would look like this:

def bootstrap_navlist(&block)
  render template: 'bootstrap/navlist', :locals => { :block => block }
end


<ul class="nav nav-list">
  <%= capture(self, &block) %>
</ul>


来源:https://stackoverflow.com/questions/12543025/rails-refactoring-html-producing-helper-method-to-use-a-partial-how-to-use-bl

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