📜 ⬆️ ⬇️

Universal numbering as a Mako template function

I think everyone faced with the need to create a "page numbers" for the site. In Pylons, somewhere there was a numerator (in webhelpers), but I did not like its functionality. If you make the numerator fast enough and flexible (not just all the numbers), then the code is not small and its cloning complicates the templates. And here Mako's template functions come to the rescue.

  1. <% def name = "draw_numeric_pages (url, page_number = None, pages_max = None)">
  2. <p>
  3. <%
  4. page_i = 0
  5. if page_number == None:
  6. page_number = c.page_number
  7. if pages_max == None:
  8. pages_max = c.pages_max
  9. %>
  10. % if page_number> 0:
  11. <a href="$[(urur%(page_number-1).replace('%%','%')}"> << / a>
  12. % endif
  13. % while page_i <= pages_max:
  14. % if page_i == page_number:
  15. ($ {page_i})
  16. % else:
  17. % if abs (page_i - page_number) <5:
  18. <a href="${(urur%(page_i).replace('%%','%')"> $ {page_i} </a>
  19. % elif abs (page_i - pages_max) <5:
  20. <a href="${(url%(page_i).replace('%%','%')) "> $ {page_i} </a>
  21. % elif abs (page_i - pages_max) <10 and abs (page_i - pages_max)> 5:
  22. .
  23. % elif page_i <5:
  24. <a href="${(urur%(page_i).replace('%%','%')"> $ {page_i} </a>
  25. % elif page_i> 5 and page_i <10:
  26. .
  27. % elif page_i> = 10 and page_i <page_number:
  28. <%
  29. page_i = page_number - 4
  30. continue
  31. %>
  32. % elif page_i> page_number and abs (page_i - pages_max)> 10:
  33. <%
  34. page_i = pages_max - 9
  35. continue
  36. %>
  37. % endif
  38. % endif
  39. <% page_i + = 1%>
  40. % end while
  41. % if page_number <pages_max:
  42. <a href="${(url%(pagepage_number+1).replace('%%','%')}">> </a>
  43. % endif
  44. </ p>
  45. </% def>


Usually I take all the functions into single .mako files for example, this function is in my std_func.mako file, according to this in the target template we do:
<%namespace name="std_func" file="/std_func.mako"/>
and then you can use our numerator:
${std_func.draw_numeric_pages("/forum/posts/%i")}
those. You can always construct a url and substitute the page number where appropriate.
In this case, I assume that the context variable contains the page_number (current page) and pages_max (maximum number of) page variables, but you can also always pass them as a function argument. An example can be seen here: mjv-art.org/jvwall/view_posts/0?lang=ru . The function there is more difficult because it replaces not only the page number but also the current language on the site.

')

Source: https://habr.com/ru/post/99521/


All Articles