Skip to content

Instantly share code, notes, and snippets.

@bjornuppeke
Created June 9, 2016 16:35
Show Gist options
  • Save bjornuppeke/b759c6b48c3fd44cd44a14b5c6cb7e73 to your computer and use it in GitHub Desktop.
Save bjornuppeke/b759c6b48c3fd44cd44a14b5c6cb7e73 to your computer and use it in GitHub Desktop.
Extends Django CMS sub menu template tag and adds pagination
from django import template
from classytags.arguments import IntegerArgument, Argument, StringArgument
from classytags.core import Options
from menus.templatetags.menu_tags import ShowSubMenu
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
register = template.Library()
class ShowPaginatedSubMenu(ShowSubMenu):
"""
show a paginated sub menu of the current nav-node.
- levels: how many levels deep
- root_level: the level to start the menu at
- nephews: the level of descendants of siblings (nephews) to show
- page_size: The Paginator page size
- template: template used to render the navigation
"""
name = 'show_paginated_sub_menu'
template = 'menu/dummy.html'
options = Options(
IntegerArgument('levels', default=100, required=False),
Argument('root_level', default=None, required=False),
IntegerArgument('nephews', default=100, required=False),
IntegerArgument('page_size', default=4, required=False),
Argument('template', default='menu/paginated_sub_menu.html', required=False),
)
def get_context(self, context, levels, root_level, nephews, page_size, template):
context = super(ShowPaginatedSubMenu, self).get_context(context, levels, root_level, nephews, template)
try:
# If there's an exception (500), default context_processors may not be called.
request = context['request']
except KeyError:
return {'template': 'menu/empty.html'}
print dir(context['current_page'])
children = context['children']
paginator = Paginator(children, page_size)
page = request.GET.get('page')
try:
paginated_children = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
paginated_children = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
paginated_children = paginator.page(paginator.num_pages)
context['children'] = paginated_children
return context
register.tag(ShowPaginatedSubMenu)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment