| 636 | def columns(thelist, n): |
| 637 | """ |
| 638 | Breaks a list into ``n`` number of columns, filling up each column to the |
| 639 | maximum equal length possible. This filter will always return ``n`` |
| 640 | columns, even if some are empty. |
| 641 | |
| 642 | Usage:: |
| 643 | |
| 644 | {% for item_column in item_list|columns:3 %} |
| 645 | <li class="column"> |
| 646 | <ul> |
| 647 | {% for item in item_column %} |
| 648 | <li><a href="#">{{ item }}</a></li> |
| 649 | {% endfor %} |
| 650 | </ul> |
| 651 | </li> |
| 652 | {% endfor %} |
| 653 | |
| 654 | """ |
| 655 | try: |
| 656 | n = int(n) |
| 657 | thelist = list(thelist) |
| 658 | except (ValueError, TypeError): |
| 659 | return [thelist] |
| 660 | |
| 661 | list_len = len(thelist) |
| 662 | split = list_len // n |
| 663 | |
| 664 | if list_len % n != 0: |
| 665 | split += 1 |
| 666 | |
| 667 | return [thelist[split*i:split*(i+1)] for i in range(n)] |
| 668 | |
| 669 | def rows(thelist, n): |
| 670 | """ |
| 671 | Breaks a list into rows with a maximum number of ``n`` elements in each. |
| 672 | |
| 673 | Usage:: |
| 674 | |
| 675 | {% for item_row in item_list|rows:4 %} |
| 676 | <li class="row"> |
| 677 | <ul> |
| 678 | {% for item in item_row %} |
| 679 | <li><a href="#">{{ item }}</a></li> |
| 680 | {% endfor %} |
| 681 | </ul> |
| 682 | </li> |
| 683 | {% endfor %} |
| 684 | |
| 685 | """ |
| 686 | try: |
| 687 | n = int(n) |
| 688 | thelist = list(thelist) |
| 689 | except (ValueError, TypeError): |
| 690 | return [thelist] |
| 691 | |
| 692 | newlists = [list() for i in range(int(ceil(len(thelist) / float(n))))] |
| 693 | |
| 694 | for i, val in enumerate(thelist): |
| 695 | newlists[i/n].append(val) |
| 696 | |
| 697 | return newlists |
| 698 | |