Rails:重构HTML生成帮助器方法以使用部分方法-如何在其中使用块? [英] Rails: Refactoring HTML producing helper method to use a partial - how to use blocks there?
问题描述
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>
该块看起来像这样,但是它可以是您喜欢的任何HTML:
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|
您可能会猜到,我不确定如何在视图中输出块.我是否应该简单地在帮助程序中捕获它并将其作为:local
变量传递?还是有更常见的方式?
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?
非常感谢.
推荐答案
在这种情况下,内容标签没有被深深地嵌套,作为助手是合理的.
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>
这篇关于Rails:重构HTML生成帮助器方法以使用部分方法-如何在其中使用块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!