【问题标题】:Rails 4: nested content_tag in methods and blocksRails 4:方法和块中的嵌套 content_tag
【发布时间】:2016-02-26 19:09:54
【问题描述】:

我想我给自己制造了一些讨厌的问题。见下文:

查看

<% tl = tablist_initialize(params[:tab], 'profile') %>

# lots of html
# ...

<%= tl.tab_content do %>
    <% tl.tab_panel 'profile' do %>
        Hello!
    <% end %>
    <% tl.tab_panel 'settings' do %>
      Sup!
    <% end %>
    <% tl.tab_panel 'notifications' do %>
      Nothing!
    <% end %>
<% end %>

助手

class TabList
    include ActionView::Helpers::TagHelper
    include ActionView::Helpers::TextHelper
    attr_accessor :output_buffer

    def initialize(tab, primary)
      @current_tab = tab
      @primary = primary
    end

    def tab_content(&block)
        content_tag(:div, :class => "tab-content", &block)
    end

    def tab_panel(id, &block)
        concat(content_tag(:div, {:class => (@current_tab == id ? "tab-pane active" : "tab-pane"),
          :role => "tabpanel", :id => id }, &block))
    end

    # other methods
    # ...
end

输出

我的计划是轻松创建引导选项卡。结果现在是这样的:

Hello! Sup! Nothing!
<div class="tab-content">
    <div class="tab-pane active" role="tabpanel" id="profile">
         Hello!
    </div>
    <div class="tab-pane" role="tabpanel" id="settings">
        Sup!
    </div>
    <div class="tab-pane" role="tabpanel" id="notifications">    
        Nothing!
    </div>
</div>

为什么是结果的第一行(Hello!Sup!Nothing!)?我认为两次输出内部块很奇怪:一次正确,一次完全在任一块之外(在开始时)。我尝试了不同的方法:省略 concat 函数,在第一个 content_tag 中围绕 yield 使用 concat,但所有这些尝试都没有给我想要的结果。

【问题讨论】:

    标签: ruby-on-rails twitter-bootstrap ruby-on-rails-4


    【解决方案1】:

    删除 tl.tab_content 行上的 = 并在每个 tl.tabl_panel 行上添加一个 =。

    <% tl.tab_content do %>
        <%= tl.tab_panel 'profile' do %>
            Hello!
        <% end %>
        <%= tl.tab_panel 'settings' do %>
          Sup!
        <% end %>
        <%= tl.tab_panel 'notifications' do %>
          Nothing!
        <% end %>
    <% end %>
    

    另外,从您的 tab_panel 方法中删除 concat

    class TabList
    include ActionView::Helpers::TagHelper
    include ActionView::Helpers::TextHelper
    attr_accessor :output_buffer
    
    def initialize(tab, primary)
      @current_tab = tab
      @primary = primary
    end
    
    def tab_content(&block)
        content_tag(:div, :class => "tab-content", &block)
    end
    
    def tab_panel(id, &block)
        content_tag(:div, {:class => (@current_tab == id ? "tab-pane active" : "tab-pane"), :role => "tabpanel", :id => id }, &block)
    end
    
    # other methods
    # ...
    end
    

    【讨论】:

    • 感谢更新,但这也没有成功。 pastie.org/10739099 它仍然会多次打印内部块内容,并发出带有 tab-content 类的外部 div。
    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    相关资源
    最近更新 更多