rapid_menu.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. __author__ = 'marcos.medeiros'
  2. import locale
  3. from django import template
  4. from django.utils.safestring import mark_safe
  5. from django.utils.html import escape
  6. from rapid.registry import registry
  7. from rapid.wrappers import ModelData
  8. from django.utils.translation import to_locale, get_language
  9. register = template.Library()
  10. try:
  11. locale.setlocale(locale.LC_ALL, str(to_locale(get_language())))
  12. except:
  13. locale.setlocale(locale.LC_ALL, str('C'))
  14. def _app_menu(app, request):
  15. models = list(app.models)
  16. models.sort(key=lambda m: ModelData(m).model_name(), cmp=locale.strcoll)
  17. sub = '<li class="menu-group"><div>%s</div><ul class="submenu">\n' % escape(app.menu_name.capitalize())
  18. has_model = False
  19. for m in models:
  20. st = registry.model_entry(m).get('list')
  21. if st:
  22. read = st.permission.model(request)
  23. if read:
  24. has_model = True
  25. cd = ModelData(st.model)
  26. sub += '<li><a href="%s">%s</a></li>\n' % (
  27. registry.get_url_of_action(m, 'list'),
  28. escape(cd.model_name_plural().title()),
  29. )
  30. sub += '</ul></li>\n'
  31. if has_model:
  32. return sub
  33. return ""
  34. @register.simple_tag
  35. def menu(request):
  36. ret = u"""
  37. <nav id="menu">
  38. <style scoped>
  39. nav li.menu-group{
  40. cursor: pointer;
  41. }
  42. nav li.menu-group.collapsed > ul{
  43. display: none;
  44. }
  45. </style>
  46. """
  47. ret += '<ul class="menu">\n'
  48. mm = registry.modules()
  49. mm.sort(key=lambda a: a.menu_name, cmp=locale.strcoll)
  50. for m in mm:
  51. ret += _app_menu(m, request)
  52. ret += u"""
  53. </ul>
  54. <script>
  55. $(document).ready(function(){
  56. $("nav li.menu-group").addClass("collapsed");
  57. $("nav li.menu-group > div").click(function(){$(this).parent().toggleClass("collapsed")});
  58. });
  59. </script>
  60. </nav>
  61. """
  62. return mark_safe(ret)