开发者

Rails: Rendering Multiple index.html.erb on a Single Page

开发者 https://www.devze.com 2023-01-05 19:45 出处:网络
I am using tabs and want to load multiple index pages into tabs. For instance: class AnimalsController < ApplicationController

I am using tabs and want to load multiple index pages into tabs. For instance:

class AnimalsController < ApplicationController
  def index
    @dogs = Dog.all
    @cats = Cat.all
  end
end

Then in my views/animals/index.html.erb

<ul class="tabs">
  <li>Dogs</li>
  <li>Cats</li>
</ul>
<div id="#dogs">
  <%= render @dogs %>
</div>
<div id=开发者_开发技巧"#cats">
  <%= render @cats %>
</div>

Is refactoring out into a partial the only way to achieve this?

I'd like to have them loaded statically at once and not have to resort to doing an Ajax.load() when the tab is clicked.


You have your answer in the question itself. Why don't you just use javascript to hide the two partials and call them when their respective tab is clicked? You don't need ajax for this at all :)

Since you did not mention the javascript library that you use, I will give a generic solution using jquery:

Also you need not add a # to your respective div's ids. Change it to this:

<ul class="tabs">
  <li id="dogs">Dogs</li>
  <li id="cats">Cats</li>
</ul>
<div id="dogs" class="subTabs">
  <%= render @dogs %><hr />
</div>
<div id="cats" class="subTabs">
  <%= render @cats %><hr />
</div>


$(document).ready(function() {
    $('.subTabs').hide(); //Hide the subTabs as soon as the DOM is loaded.

    $('li').live('click', function(e) {
        $('.subTabs').hide(); //Calling this again so as to remove an already loaded
                                tab, if any. You can refactor this part to make it
                                even simpler.
        $('body').find('.subTabs').attr('id',$(this).attr('id')).show();
             //This finds the ".subTabs" whose id is the same as the "li" id that
               was clicked and shows it. Ofcourse, even this can be made even more
               compact had i known your entire DOM structure.     
    });
});

Edit: You also have to make sure that you style it using CSS to make it look more like tabs if you haven't already. :)

Hope this helps. :)


You typically only want to use a partial if you are using the same or almost the same code in more than one place.

When you say "index page", do you really want to use the same code that is used in an index of another controller? If so, then a partial is the best strategy.

Don't use JavaScript to solve a layout / code organization problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消