1

ビューの抽象コンポーネントを作成したいのですが、それらがレンダリングされる方法を明らかにしていません。例は、ブートストラップのタブのようなタブ付きのナビゲーション ボックスです。

私の見解では、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>

タブ「コンテンツ」のレンダリングを延期する試みはすべて失敗しました。私が取った 3 つのアプローチを示す最小限の Rails アプリを作成しました。

application_helper.rb とwelcome#show ビューを見てください。そのようなことを行う正しい方法は何ですか?

4

1 に答える 1

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 
于 2012-06-13T12:29:28.240 に答える