Commits

Anonymous committed ca75c50

Initial Checkin

  • Participants

Comments (0)

Files changed (6)

+"""
+Copyright (c) 2007-2008, Dj Gilcrease
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+"""
+from django_nav.base import nav_groups, Nav, NavOption
+
+def autodiscover():
+    """
+    Auto-discover INSTALLED_APPS tabs.py modules and fail silently when
+    not present. This forces an import on them to register any tabs they
+    may want.
+    """
+    import imp
+    from django.conf import settings
+
+    for app in settings.INSTALLED_APPS:
+        # For each app, we need to look for an tabs.py inside that app's
+        # package. We can't use os.path here -- recall that modules may be
+        # imported different ways (think zip files) -- so we need to get
+        # the app's __path__ and look for cron.py on that path.
+
+        # Step 1: find out the app's __path__ Import errors here will (and
+        # should) bubble up, but a missing __path__ (which is legal, but weird)
+        # fails silently -- apps that do weird things with __path__ might
+        # need to roll their own cron registration.
+        try:
+            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__
+        except AttributeError:
+            continue
+
+        # Step 2: use imp.find_module to find the app's tabs.py. For some
+        # reason imp.find_module raises ImportError if the app can't be found
+        # but doesn't actually try to import the module. So skip this app if
+        # its tabs.py doesn't exist
+        try:
+            imp.find_module('nav', app_path)
+        except ImportError:
+            continue
+
+        # Step 3: import the app's tabs file. If this has errors we want them
+        # to bubble up.
+        __import__("%s.nav" % app)
+"""
+Copyright (c) 2007-2008, Dj Gilcrease
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+"""
+from django.core.urlresolvers import reverse
+
+class NavType(object):
+    name = u'I Forgot to Name this'
+    view = None
+    args = ()
+    kwargs ={}
+    options = []
+
+    def get_absolute_url(self):
+        if view:
+            return reverse(self.view, *self.args, **self.kwargs)
+
+        return '#'
+
+class NavOption(NavType):
+    template = 'django_nav/option.html'
+
+class Nav(NavType):
+    template = 'django_nav/nav.html'
+    nav_group = 'main'
+
+class NavStore(object):
+    _groups = {}
+    def __new__(cls):
+        it = cls.__dict__.get("__it__")
+        if it is not None:
+            return it
+        cls.__it__ = it = object.__new__(cls)
+        return it
+
+    def register(self, nav):
+        """
+            Register the given Nav
+        """
+        try:
+            nav = nav()
+        except TypeError:
+            pass
+
+        if not isinstance(nav, NavType):
+            raise TypeError("You can only register a Nav not a %r" % nav)
+
+        if not self._groups.has_key(nav.nav_group):
+            self._groups[nav.nav_group] = []
+
+        if nav not in self._groups[nav.nav_group]:
+            self._groups[nav.nav_group].append(nav)
+
+    def __getitem__(self, nav_group):
+        return self._groups.get(nav_group, [])
+
+    def __setitem__(self, *args):
+        raise AttributeError
+
+nav_groups = NavStore()

File templates/django_nav/nav.html

+<li onclick="window.location = '{{ nav.get_absolute_url }}'" class="nav {{ nav.nav_group }}{% if nav.active %} active{% endif %}">
+    <a href="{{ nav.get_absolute_url }}">{{ nav.name }}</a>
+    {% if nav.option_list %}<ul class="options">
+    {% for option in nav.option_list %}
+    {{ option }}{% endfor %}
+    </ul>{% endif %}
+</li>

File templates/django_nav/option.html

+<li onclick="window.location = '{{ option.get_absolute_url }}'" class="nav option">
+    <a href="{{ option.get_absolute_url }}">{{ option.name }}</a>
+    {% if option.option_list %}<ul class="options">
+    {% for opt in option.option_list %}
+    {{ opt }}{% endfor %}
+    </ul>{% endif %}
+</li>

File templatetags/__init__.py

Empty file added.

File templatetags/tabs.py

+import re
+
+from django import template
+
+from django_nav import nav_groups
+
+register = template.Library()
+
+class GetNavNode(template.Node):
+    def __init__(self, nav_group, var_name):
+            self.nav_group = nav_group
+            self.var_name = var_name
+            self.context = {'request': ''}
+
+    def render(self, context):
+        self.context = context
+        self.build_nav()
+        return ''
+
+    def build_nav(self):
+        self.context[self.var_name] = []
+
+        for nav in nav_groups[self.nav_group]:
+            nav.option_list = self.build_options(nav.options)
+            nav.active = False
+            if self.context['request'].path == nav.get_absolute_url():
+                nav.active = True
+
+            self.context[self.var_name].append(template.loader.render_to_string(nav.template, {'nav': nav}))
+
+    def build_options(self, tab_options):
+        options = []
+        for option in tab_options:
+            option.option_list = self.build_options(option.options)
+            options.append(template.loader.render_to_string(option.template, {'option': option}))
+
+        return options
+
+def get_nav(parser, token):
+    try:
+        tag_name, args = token.contents.split(None, 1)
+    except ValueError:
+        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
+
+    m = re.search(r'(.*?) as (\w+)', args)
+    if not m:
+        nav_group = var_name = args.strip("'").strip('"')
+    else:
+        nav_group, var_name = m.groups()
+        nav_group = nav_group.strip("'").strip('"')
+
+    return GetTabsNode(nav_group, var_name)
+
+register.tag('get_nav', get_nav)