2012-06-12 41 views
1

我想創建自己的看法抽象成分,不透露他們將要呈現的方式。 該示例是一個選項卡式導航盒,如tabs from bootstrapDRY視分量的意見

在我看來,我想寫s.th.如:

= tab_section(self) do 
     - tab 'tab1' do 
     %p tab1 content 
     = link_to example_var, "#top" 
     - tab 'tab2' do 
     %p tab2 content 
     = link_to 'http://example.com', "#top" 

然後應該呈現給s.th.像這樣:

 <ul> 
      <li>tab1</li> 
      <li>tab2</li> 
     </ul> 
     <div class='content'> 
      <div class='tab'> 
      <p>tab1 content</p> 
      <a href='#top'>this could also be an @var from the controller</a> 
      </div> 
      <div class='tab'> 
      <p>tab2 content</p> 
      <a href='#top'>http://example.com</a> 
      </div> 
     </div> 

我推遲標籤'內容'渲染失敗的所有嘗試都失敗了。我創建了一個minimal rails app,演示了我採用的三種方法。

看看的application_helper.rb和歡迎#放映視圖。 做這種事情的正確方法是什麼?

回答

1

我得到了一些支持,並找到了以下解決方案:

外「組件」必須被傳遞到塊時致電內部函數:

 = tab_section2 do |section| 
     - section.tab 'tab1' do 
      %p tab1 content 
      = link_to example_var, "#top" 
     - section.tab 'tab2' do 
      %p tab2 content 
      = link_to 'http://example.com', "#top" 

因爲我們不需要將塊綁定到tab_section實例(以前使用instance_exec完成),我們可以直接生成塊。

 def tab_section2(&blk) 
     raise "Y U NO SUPPLY block?" unless block_given? 
     ts = TabSection2.new(self, self) 
     yield(ts) 
     render :partial => '/tab2', locals: {section: ts} 
     end 

局部呈現選項卡的輸出渲染功能:

%ul 
     - section.tabs.each do |tab| 
     %li= tab.name 
    .content 
     - section.tabs.each do |tab| 
     .tab 
      = tab.render.html_safe 

其被實現如下:

class Tab2 

     attr_reader :name, :blk 
     def initialize(name, context, &blk) 
     @context = context 
     @name = name 
     @blk = blk 
     end 

     def render 
     @context.capture_haml(&@blk) 
     end 
    end 

    class TabSection2 
     attr_reader :tabs 

     def initialize(context) 
     @context = context 
     @tabs = [] 
     end 

     def tab(name, &blk) 
     raise "Y U NO SUPPLY block?" unless block_given? 
     @tabs << Tab2.new(name, @context, &blk) 
     end 
    end