Debian Codegraph @

paginate/__init__.py

raw symbols SCIP
1 # Copyright (c) 2007-2012 Christoph Haas <[email protected]>
2 # See the file LICENSE for copying permission.
3
4 """
5 paginate: helps split up large collections into individual pages
6 ================================================================
7
8 What is pagination?
9 ---------------------
10
11 This module helps split large lists of items into pages. The user is shown one page at a time and
12 can navigate to other pages. Imagine you are offering a company phonebook and let the user search
13 the entries. The entire search result may contains 23 entries but you want to display no more than
14 10 entries at once. The first page contains entries 1-10, the second 11-20 and the third 21-23.
15 Each "Page" instance represents the items of one of these three pages.
16
17 See the documentation of the "Page" class for more information.
18
19 How do I use it?
20 ------------------
21
22 A page of items is represented by the *Page* object. A *Page* gets initialized with these arguments:
23
24 - The collection of items to pick a range from. Usually just a list.
25 - The page number you want to display. Default is 1: the first page.
26
27 Now we can make up a collection and create a Page instance of it::
28
29 # Create a sample collection of 1000 items
30 >> my_collection = range(1000)
31
32 # Create a Page object for the 3rd page (20 items per page is the default)
33 >> my_page = Page(my_collection, page=3)
34
35 # The page object can be printed as a string to get its details
36 >> str(my_page)
37 Page:
38 Collection type: <type 'range'>
39 Current page: 3
40 First item: 41
41 Last item: 60
42 First page: 1
43 Last page: 50
44 Previous page: 2
45 Next page: 4
46 Items per page: 20
47 Number of items: 1000
48 Number of pages: 50
49
50 # Print a list of items on the current page
51 >> my_page.items
52 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
53
54 # The *Page* object can be used as an iterator:
55 >> for my_item in my_page: print(my_item)
56 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
57
58 # The .pager() method returns an HTML fragment with links to surrounding pages.
59 >> my_page.pager(url="http://example.org/foo/page=$page")
60
61 <a href="http://example.org/foo/page=1">1</a>
62 <a href="http://example.org/foo/page=2">2</a>
63 3
64 <a href="http://example.org/foo/page=4">4</a>
65 <a href="http://example.org/foo/page=5">5</a>
66 ..
67 <a href="http://example.org/foo/page=50">50</a>'
68
69 # Without the HTML it would just look like:
70 # 1 2 [3] 4 5 .. 50
71
72 # The pager can be customized:
73 >> my_page.pager('$link_previous ~3~ $link_next (Page $page of $page_count)',
74 url="http://example.org/foo/page=$page")
75
76 <a href="http://example.org/foo/page=2">&lt;</a>
77 <a href="http://example.org/foo/page=1">1</a>
78 <a href="http://example.org/foo/page=2">2</a>
79 3
80 <a href="http://example.org/foo/page=4">4</a>
81 <a href="http://example.org/foo/page=5">5</a>
82 <a href="http://example.org/foo/page=6">6</a>
83 ..
84 <a href="http://example.org/foo/page=50">50</a>
85 <a href="http://example.org/foo/page=4">&gt;</a>
86 (Page 3 of 50)
87
88 # Without the HTML it would just look like:
89 # 1 2 [3] 4 5 6 .. 50 > (Page 3 of 50)
90
91 # The url argument to the pager method can be omitted when an url_maker is
92 # given during instantiation:
93 >> my_page = Page(my_collection, page=3,
94 url_maker=lambda p: "http://example.org/%s" % p)
95 >> page.pager()
96
97 There are some interesting parameters that customize the Page's behavior. See the documentation on
98 ``Page`` and ``Page.pager()``.
99
100
101 Notes
102 -------
103
104 Page numbers and item numbers start at 1. This concept has been used because users expect that the
105 first page has number 1 and the first item on a page also has number 1. So if you want to use the
106 page's items by their index number please note that you have to subtract 1.
107 """
108
109 __author__ = "Christoph Haas"
110 __copyright__ = "Copyright 2007-2016 Christoph Haas and contributors"
111 __credits__ = ["Mike Orr"]
112 __license__ = "MIT"
113 __version__ = "0.5.4"
114 __maintainer__ = "Marcin Lulek, Luke Crooks"
115 __email__ = "[email protected], [email protected]"
116 __status__ = "Beta"
117
118
119 import re
120 from string import Template
121 import sys
122
123 # are we running at least python 3.x ?
124 PY3 = sys.version_info[0] >= 3
125
126 if PY3:
127 unicode = str
128
129
130 # Since the items on a page are mainly a list we subclass the "list" type
131 class Page(list):
132 """A list/iterator representing the items on one page of a larger collection.
133
134 An instance of the "Page" class is created from a _collection_ which is any
135 list-like object that allows random access to its elements.
136
137 The instance works as an iterator running from the first item to the last item on the given
138 page. The Page.pager() method creates a link list allowing the user to go to other pages.
139
140 A "Page" does not only carry the items on a certain page. It gives you additional information
141 about the page in these "Page" object attributes:
142
143 item_count
144 Number of items in the collection
145
146 **WARNING:** Unless you pass in an item_count, a count will be
147 performed on the collection every time a Page instance is created.
148
149 page
150 Number of the current page
151
152 items_per_page
153 Maximal number of items displayed on a page
154
155 first_page
156 Number of the first page - usually 1 :)
157
158 last_page
159 Number of the last page
160
161 previous_page
162 Number of the previous page. If this is the first page it returns None.
163
164 next_page
165 Number of the next page. If this is the last page it returns None.
166
167 page_count
168 Number of pages
169
170 items
171 Sequence/iterator of items on the current page
172
173 first_item
174 Index of first item on the current page - starts with 1
175
176 last_item
177 Index of last item on the current page
178 """
179
180 def __init__(
181 self,
182 collection,
183 page=1,
184 items_per_page=20,
185 item_count=None,
186 wrapper_class=None,
187 url_maker=None,
188 **kwargs
189 ):
190 """Create a "Page" instance.
191
192 Parameters:
193
194 collection
195 Sequence representing the collection of items to page through.
196
197 page
198 The requested page number - starts with 1. Default: 1.
199
200 items_per_page
201 The maximal number of items to be displayed per page.
202 Default: 20.
203
204 item_count (optional)
205 The total number of items in the collection - if known.
206 If this parameter is not given then the paginator will count
207 the number of elements in the collection every time a "Page"
208 is created. Giving this parameter will speed up things. In a busy
209 real-life application you may want to cache the number of items.
210
211 url_maker (optional)
212 Callback to generate the URL of other pages, given its numbers.
213 Must accept one int parameter and return a URI string.
214 """
215 if collection is not None:
216 if wrapper_class is None:
217 # Default case. The collection is already a list-type object.
218 self.collection = collection
219 else:
220 # Special case. A custom wrapper class is used to access elements of the collection.
221 self.collection = wrapper_class(collection)
222 else:
223 self.collection = []
224
225 self.collection_type = type(collection)
226
227 if url_maker is not None:
228 self.url_maker = url_maker
229 else:
230 self.url_maker = self._default_url_maker
231
232 # Assign kwargs to self
233 self.kwargs = kwargs
234
235 # The self.page is the number of the current page.
236 # The first page has the number 1!
237 try:
238 self.page = int(page) # make it int() if we get it as a string
239 except (ValueError, TypeError):
240 self.page = 1
241 # normally page should be always at least 1 but the original maintainer
242 # decided that for empty collection and empty page it can be...0? (based on tests)
243 # preserving behavior for BW compat
244 if self.page < 1:
245 self.page = 1
246
247 self.items_per_page = items_per_page
248
249 # We subclassed "list" so we need to call its init() method
250 # and fill the new list with the items to be displayed on the page.
251 # We use list() so that the items on the current page are retrieved
252 # only once. In an SQL context that could otherwise lead to running the
253 # same SQL query every time items would be accessed.
254 # We do this here, prior to calling len() on the collection so that a
255 # wrapper class can execute a query with the knowledge of what the
256 # slice will be (for efficiency) and, in the same query, ask for the
257 # total number of items and only execute one query.
258 try:
259 first = (self.page - 1) * items_per_page
260 last = first + items_per_page
261 self.items = list(self.collection[first:last])
262 except (KeyError, TypeError) as exc:
263 raise TypeError(
264 "Your collection of type {} cannot be handled "
265 "by paginate.".format(type(self.collection))
266 )
267
268 # Unless the user tells us how many items the collections has
269 # we calculate that ourselves.
270 if item_count is not None:
271 self.item_count = item_count
272 else:
273 self.item_count = len(self.collection)
274
275 # Compute the number of the first and last available page
276 if self.item_count > 0:
277 self.first_page = 1
278 self.page_count = ((self.item_count - 1) // self.items_per_page) + 1
279 self.last_page = self.first_page + self.page_count - 1
280
281 # Make sure that the requested page number is the range of valid pages
282 if self.page > self.last_page:
283 self.page = self.last_page
284 elif self.page < self.first_page:
285 self.page = self.first_page
286
287 # Note: the number of items on this page can be less than
288 # items_per_page if the last page is not full
289 self.first_item = (self.page - 1) * items_per_page + 1
290 self.last_item = min(self.first_item + items_per_page - 1, self.item_count)
291
292 # Links to previous and next page
293 if self.page > self.first_page:
294 self.previous_page = self.page - 1
295 else:
296 self.previous_page = None
297
298 if self.page < self.last_page:
299 self.next_page = self.page + 1
300 else:
301 self.next_page = None
302
303 # No items available
304 else:
305 self.first_page = None
306 self.page_count = 0
307 self.last_page = None
308 self.first_item = None
309 self.last_item = None
310 self.previous_page = None
311 self.next_page = None
312 self.items = []
313
314 # This is a subclass of the 'list' type. Initialise the list now.
315 list.__init__(self, self.items)
316
317 def __str__(self):
318 return (
319 "Page:\n"
320 "Collection type: {0.collection_type}\n"
321 "Current page: {0.page}\n"
322 "First item: {0.first_item}\n"
323 "Last item: {0.last_item}\n"
324 "First page: {0.first_page}\n"
325 "Last page: {0.last_page}\n"
326 "Previous page: {0.previous_page}\n"
327 "Next page: {0.next_page}\n"
328 "Items per page: {0.items_per_page}\n"
329 "Total number of items: {0.item_count}\n"
330 "Number of pages: {0.page_count}\n"
331 ).format(self)
332
333 def __repr__(self):
334 return "<paginate.Page: Page {0}/{1}>".format(self.page, self.page_count)
335
336 def pager(
337 self,
338 format="~2~",
339 url=None,
340 show_if_single_page=False,
341 separator=" ",
342 symbol_first="&lt;&lt;",
343 symbol_last="&gt;&gt;",
344 symbol_previous="&lt;",
345 symbol_next="&gt;",
346 link_attr=None,
347 curpage_attr=None,
348 dotdot_attr=None,
349 link_tag=None,
350 ):
351 """
352 Return string with links to other pages (e.g. '1 .. 5 6 7 [8] 9 10 11 .. 50').
353
354 format:
355 Format string that defines how the pager is rendered. The string
356 can contain the following $-tokens that are substituted by the
357 string.Template module:
358
359 - $first_page: number of first reachable page
360 - $last_page: number of last reachable page
361 - $page: number of currently selected page
362 - $page_count: number of reachable pages
363 - $items_per_page: maximal number of items per page
364 - $first_item: index of first item on the current page
365 - $last_item: index of last item on the current page
366 - $item_count: total number of items
367 - $link_first: link to first page (unless this is first page)
368 - $link_last: link to last page (unless this is last page)
369 - $link_previous: link to previous page (unless this is first page)
370 - $link_next: link to next page (unless this is last page)
371
372 To render a range of pages the token '~3~' can be used. The
373 number sets the radius of pages around the current page.
374 Example for a range with radius 3:
375
376 '1 .. 5 6 7 [8] 9 10 11 .. 50'
377
378 Default: '~2~'
379
380 url
381 The URL that page links will point to. Make sure it contains the string
382 $page which will be replaced by the actual page number.
383 Must be given unless a url_maker is specified to __init__, in which
384 case this parameter is ignored.
385
386 symbol_first
387 String to be displayed as the text for the $link_first link above.
388
389 Default: '&lt;&lt;' (<<)
390
391 symbol_last
392 String to be displayed as the text for the $link_last link above.
393
394 Default: '&gt;&gt;' (>>)
395
396 symbol_previous
397 String to be displayed as the text for the $link_previous link above.
398
399 Default: '&lt;' (<)
400
401 symbol_next
402 String to be displayed as the text for the $link_next link above.
403
404 Default: '&gt;' (>)
405
406 separator:
407 String that is used to separate page links/numbers in the above range of pages.
408
409 Default: ' '
410
411 show_if_single_page:
412 if True the navigator will be shown even if there is only one page.
413
414 Default: False
415
416 link_attr (optional)
417 A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
418 be used to define a CSS style or class to customize the look of links.
419
420 Example: { 'style':'border: 1px solid green' }
421 Example: { 'class':'pager_link' }
422
423 curpage_attr (optional)
424 A dictionary of attributes that get added to the current page number in the pager (which
425 is obviously not a link). If this dictionary is not empty then the elements will be
426 wrapped in a SPAN tag with the given attributes.
427
428 Example: { 'style':'border: 3px solid blue' }
429 Example: { 'class':'pager_curpage' }
430
431 dotdot_attr (optional)
432 A dictionary of attributes that get added to the '..' string in the pager (which is
433 obviously not a link). If this dictionary is not empty then the elements will be wrapped
434 in a SPAN tag with the given attributes.
435
436 Example: { 'style':'color: #808080' }
437 Example: { 'class':'pager_dotdot' }
438
439 link_tag (optional)
440 A callable that accepts single argument `page` (page link information)
441 and generates string with html that represents the link for specific page.
442 Page objects are supplied from `link_map()` so the keys are the same.
443
444
445 """
446 link_attr = link_attr or {}
447 curpage_attr = curpage_attr or {}
448 dotdot_attr = dotdot_attr or {}
449 self.curpage_attr = curpage_attr
450 self.separator = separator
451 self.link_attr = link_attr
452 self.dotdot_attr = dotdot_attr
453 self.url = url
454 self.link_tag = link_tag or self.default_link_tag
455
456 # Don't show navigator if there is no more than one page
457 if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page):
458 return ""
459
460 regex_res = re.search(r"~(\d+)~", format)
461 if regex_res:
462 radius = regex_res.group(1)
463 else:
464 radius = 2
465 radius = int(radius)
466 self.radius = radius
467 link_map = self.link_map(
468 format=format,
469 url=url,
470 show_if_single_page=show_if_single_page,
471 separator=separator,
472 symbol_first=symbol_first,
473 symbol_last=symbol_last,
474 symbol_previous=symbol_previous,
475 symbol_next=symbol_next,
476 link_attr=link_attr,
477 curpage_attr=curpage_attr,
478 dotdot_attr=dotdot_attr,
479 )
480 links_markup = self._range(link_map, radius)
481
482 # Replace ~...~ in token format by range of pages
483 result = re.sub(r"~(\d+)~", links_markup, format)
484
485 link_first = (
486 self.page > self.first_page and self.link_tag(link_map["first_page"]) or ""
487 )
488 link_last = (
489 self.page < self.last_page and self.link_tag(link_map["last_page"]) or ""
490 )
491 link_previous = (
492 self.previous_page and self.link_tag(link_map["previous_page"]) or ""
493 )
494 link_next = self.next_page and self.link_tag(link_map["next_page"]) or ""
495 # Interpolate '$' variables
496 result = Template(result).safe_substitute(
497 {
498 "first_page": self.first_page,
499 "last_page": self.last_page,
500 "page": self.page,
501 "page_count": self.page_count,
502 "items_per_page": self.items_per_page,
503 "first_item": self.first_item,
504 "last_item": self.last_item,
505 "item_count": self.item_count,
506 "link_first": link_first,
507 "link_last": link_last,
508 "link_previous": link_previous,
509 "link_next": link_next,
510 }
511 )
512
513 return result
514
515 def link_map(
516 self,
517 format="~2~",
518 url=None,
519 show_if_single_page=False,
520 separator=" ",
521 symbol_first="&lt;&lt;",
522 symbol_last="&gt;&gt;",
523 symbol_previous="&lt;",
524 symbol_next="&gt;",
525 link_attr=None,
526 curpage_attr=None,
527 dotdot_attr=None,
528 ):
529 """ Return map with links to other pages if default pager() function is not suitable solution.
530 format:
531 Format string that defines how the pager would be normally rendered rendered. Uses same arguments as pager()
532 method, but returns a simple dictionary in form of:
533 {'current_page': {'attrs': {},
534 'href': 'http://example.org/foo/page=1',
535 'value': 1},
536 'first_page': {'attrs': {},
537 'href': 'http://example.org/foo/page=1',
538 'type': 'first_page',
539 'value': 1},
540 'last_page': {'attrs': {},
541 'href': 'http://example.org/foo/page=8',
542 'type': 'last_page',
543 'value': 8},
544 'next_page': {'attrs': {}, 'href': 'HREF', 'type': 'next_page', 'value': 2},
545 'previous_page': None,
546 'range_pages': [{'attrs': {},
547 'href': 'http://example.org/foo/page=1',
548 'type': 'current_page',
549 'value': 1},
550 ....
551 {'attrs': {}, 'href': '', 'type': 'span', 'value': '..'}]}
552
553
554 The string can contain the following $-tokens that are substituted by the
555 string.Template module:
556
557 - $first_page: number of first reachable page
558 - $last_page: number of last reachable page
559 - $page: number of currently selected page
560 - $page_count: number of reachable pages
561 - $items_per_page: maximal number of items per page
562 - $first_item: index of first item on the current page
563 - $last_item: index of last item on the current page
564 - $item_count: total number of items
565 - $link_first: link to first page (unless this is first page)
566 - $link_last: link to last page (unless this is last page)
567 - $link_previous: link to previous page (unless this is first page)
568 - $link_next: link to next page (unless this is last page)
569
570 To render a range of pages the token '~3~' can be used. The
571 number sets the radius of pages around the current page.
572 Example for a range with radius 3:
573
574 '1 .. 5 6 7 [8] 9 10 11 .. 50'
575
576 Default: '~2~'
577
578 url
579 The URL that page links will point to. Make sure it contains the string
580 $page which will be replaced by the actual page number.
581 Must be given unless a url_maker is specified to __init__, in which
582 case this parameter is ignored.
583
584 symbol_first
585 String to be displayed as the text for the $link_first link above.
586
587 Default: '&lt;&lt;' (<<)
588
589 symbol_last
590 String to be displayed as the text for the $link_last link above.
591
592 Default: '&gt;&gt;' (>>)
593
594 symbol_previous
595 String to be displayed as the text for the $link_previous link above.
596
597 Default: '&lt;' (<)
598
599 symbol_next
600 String to be displayed as the text for the $link_next link above.
601
602 Default: '&gt;' (>)
603
604 separator:
605 String that is used to separate page links/numbers in the above range of pages.
606
607 Default: ' '
608
609 show_if_single_page:
610 if True the navigator will be shown even if there is only one page.
611
612 Default: False
613
614 link_attr (optional)
615 A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
616 be used to define a CSS style or class to customize the look of links.
617
618 Example: { 'style':'border: 1px solid green' }
619 Example: { 'class':'pager_link' }
620
621 curpage_attr (optional)
622 A dictionary of attributes that get added to the current page number in the pager (which
623 is obviously not a link). If this dictionary is not empty then the elements will be
624 wrapped in a SPAN tag with the given attributes.
625
626 Example: { 'style':'border: 3px solid blue' }
627 Example: { 'class':'pager_curpage' }
628
629 dotdot_attr (optional)
630 A dictionary of attributes that get added to the '..' string in the pager (which is
631 obviously not a link). If this dictionary is not empty then the elements will be wrapped
632 in a SPAN tag with the given attributes.
633
634 Example: { 'style':'color: #808080' }
635 Example: { 'class':'pager_dotdot' }
636 """
637 link_attr = link_attr or {}
638 curpage_attr = curpage_attr or {}
639 dotdot_attr = dotdot_attr or {}
640 self.curpage_attr = curpage_attr
641 self.separator = separator
642 self.link_attr = link_attr
643 self.dotdot_attr = dotdot_attr
644 self.url = url
645
646 regex_res = re.search(r"~(\d+)~", format)
647 if regex_res:
648 radius = regex_res.group(1)
649 else:
650 radius = 2
651 radius = int(radius)
652 self.radius = radius
653
654 # Compute the first and last page number within the radius
655 # e.g. '1 .. 5 6 [7] 8 9 .. 12'
656 # -> leftmost_page = 5
657 # -> rightmost_page = 9
658 leftmost_page = (
659 max(self.first_page, (self.page - radius)) if self.first_page else None
660 )
661 rightmost_page = (
662 min(self.last_page, (self.page + radius)) if self.last_page else None
663 )
664
665 nav_items = {
666 "first_page": None,
667 "last_page": None,
668 "previous_page": None,
669 "next_page": None,
670 "current_page": None,
671 "radius": self.radius,
672 "range_pages": [],
673 }
674
675 if leftmost_page is None or rightmost_page is None:
676 return nav_items
677
678 nav_items["first_page"] = {
679 "type": "first_page",
680 "value": unicode(symbol_first),
681 "attrs": self.link_attr,
682 "number": self.first_page,
683 "href": self.url_maker(self.first_page),
684 }
685
686 # Insert dots if there are pages between the first page
687 # and the currently displayed page range
688 if leftmost_page - self.first_page > 1:
689 # Wrap in a SPAN tag if dotdot_attr is set
690 nav_items["range_pages"].append(
691 {
692 "type": "span",
693 "value": "..",
694 "attrs": self.dotdot_attr,
695 "href": "",
696 "number": None,
697 }
698 )
699
700 for thispage in range(leftmost_page, rightmost_page + 1):
701 # Highlight the current page number and do not use a link
702 if thispage == self.page:
703 # Wrap in a SPAN tag if curpage_attr is set
704 nav_items["range_pages"].append(
705 {
706 "type": "current_page",
707 "value": unicode(thispage),
708 "number": thispage,
709 "attrs": self.curpage_attr,
710 "href": self.url_maker(thispage),
711 }
712 )
713 nav_items["current_page"] = {
714 "value": thispage,
715 "attrs": self.curpage_attr,
716 "type": "current_page",
717 "href": self.url_maker(thispage),
718 }
719 # Otherwise create just a link to that page
720 else:
721 nav_items["range_pages"].append(
722 {
723 "type": "page",
724 "value": unicode(thispage),
725 "number": thispage,
726 "attrs": self.link_attr,
727 "href": self.url_maker(thispage),
728 }
729 )
730
731 # Insert dots if there are pages between the displayed
732 # page numbers and the end of the page range
733 if self.last_page - rightmost_page > 1:
734 # Wrap in a SPAN tag if dotdot_attr is set
735 nav_items["range_pages"].append(
736 {
737 "type": "span",
738 "value": "..",
739 "attrs": self.dotdot_attr,
740 "href": "",
741 "number": None,
742 }
743 )
744
745 # Create a link to the very last page (unless we are on the last
746 # page or there would be no need to insert '..' spacers)
747 nav_items["last_page"] = {
748 "type": "last_page",
749 "value": unicode(symbol_last),
750 "attrs": self.link_attr,
751 "href": self.url_maker(self.last_page),
752 "number": self.last_page,
753 }
754
755 nav_items["previous_page"] = {
756 "type": "previous_page",
757 "value": unicode(symbol_previous),
758 "attrs": self.link_attr,
759 "number": self.previous_page or self.first_page,
760 "href": self.url_maker(self.previous_page or self.first_page),
761 }
762
763 nav_items["next_page"] = {
764 "type": "next_page",
765 "value": unicode(symbol_next),
766 "attrs": self.link_attr,
767 "number": self.next_page or self.last_page,
768 "href": self.url_maker(self.next_page or self.last_page),
769 }
770
771 return nav_items
772
773 def _range(self, link_map, radius):
774 """
775 Return range of linked pages to substitute placeholder in pattern
776 """
777
778 leftmost_page = max(self.first_page, (self.page - radius))
779 rightmost_page = min(self.last_page, (self.page + radius))
780
781 nav_items = []
782 # Create a link to the first page (unless we are on the first page
783 # or there would be no need to insert '..' spacers)
784 if self.page != self.first_page and self.first_page < leftmost_page:
785 page = link_map["first_page"].copy()
786 page["value"] = unicode(page["number"])
787 nav_items.append(self.link_tag(page))
788
789 for item in link_map["range_pages"]:
790 nav_items.append(self.link_tag(item))
791
792 # Create a link to the very last page (unless we are on the last
793 # page or there would be no need to insert '..' spacers)
794 if self.page != self.last_page and rightmost_page < self.last_page:
795 page = link_map["last_page"].copy()
796 page["value"] = unicode(page["number"])
797 nav_items.append(self.link_tag(page))
798
799 return self.separator.join(nav_items)
800
801 def _default_url_maker(self, page_number):
802 if self.url is None:
803 raise Exception(
804 "You need to specify a 'url' parameter containing a '$page' placeholder."
805 )
806
807 if "$page" not in self.url:
808 raise Exception("The 'url' parameter must contain a '$page' placeholder.")
809
810 return self.url.replace("$page", unicode(page_number))
811
812 @staticmethod
813 def default_link_tag(item):
814 """
815 Create an A-HREF tag that points to another page.
816 """
817 text = item["value"]
818 target_url = item["href"]
819
820 if not item["href"] or item["type"] in ("span", "current_page"):
821 if item["attrs"]:
822 text = make_html_tag("span", **item["attrs"]) + text + "</span>"
823 return text
824
825 return make_html_tag("a", text=text, href=target_url, **item["attrs"])
826
827
828 def make_html_tag(tag, text=None, **params):
829 """Create an HTML tag string.
830
831 tag
832 The HTML tag to use (e.g. 'a', 'span' or 'div')
833
834 text
835 The text to enclose between opening and closing tag. If no text is specified then only
836 the opening tag is returned.
837
838 Example::
839 make_html_tag('a', text="Hello", href="/another/page")
840 -> <a href="/another/page">Hello</a>
841
842 To use reserved Python keywords like "class" as a parameter prepend it with
843 an underscore. Instead of "class='green'" use "_class='green'".
844
845 Warning: Quotes and apostrophes are not escaped."""
846 params_string = ""
847
848 # Parameters are passed. Turn the dict into a string like "a=1 b=2 c=3" string.
849 for key, value in sorted(params.items()):
850 # Strip off a leading underscore from the attribute's key to allow attributes like '_class'
851 # to be used as a CSS class specification instead of the reserved Python keyword 'class'.
852 key = key.lstrip("_")
853
854 params_string += u' {0}="{1}"'.format(key, value)
855
856 # Create the tag string
857 tag_string = u"<{0}{1}>".format(tag, params_string)
858
859 # Add text and closing tag if required.
860 if text:
861 tag_string += u"{0}</{1}>".format(text, tag)
862
863 return tag_string