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