Skip to content

Commit

Permalink
Template tag can now optionally return a default value when reverse r…
Browse files Browse the repository at this point in the history
…aises NoReverseMatch
  • Loading branch information
mkoistinen committed Apr 20, 2015
1 parent 0792052 commit 4807741
Showing 1 changed file with 34 additions and 11 deletions.
45 changes: 34 additions & 11 deletions aldryn_apphooks_config/templatetags/apphooks_config_tags.py
Expand Up @@ -6,6 +6,7 @@

from django import template
from django.core import urlresolvers
from django.core.urlresolvers import NoReverseMatch

from ..utils import get_app_instance

Expand All @@ -17,10 +18,17 @@
def namespace_url(context, view_name, *args, **kwargs):
"""
Returns an absolute URL matching named view with its parameters and the
provided application instance namespace. If no namespace is passed as a
kwarg (or it is "" or None), this templatetag will look into the request
object for the app_config's namespace. If there is still no namespace found,
this tag will act like the normal {% url ... %} tag.
provided application instance namespace.
If no namespace is passed as a kwarg (or it is "" or None), this templatetag
will look into the request object for the app_config's namespace. If there
is still no namespace found, this tag will act like the normal {% url ... %}
template tag.
Normally, this tag will return whatever is returned by the ultimate call to
reverse, which also means it will raise NoReverseMatch if reverse() cannot
find a match. This behaviour can be override by suppling a 'default' kwarg
with the value of what should be returned when no match is found.
"""

namespace = kwargs.pop('namespace', None)
Expand All @@ -31,11 +39,26 @@ def namespace_url(context, view_name, *args, **kwargs):
if namespace:
namespace += ":"

reverse = partial(urlresolvers.reverse, '{0:s}{1:s}'.format(namespace, view_name))
reverse = partial(
urlresolvers.reverse, '{0:s}{1:s}'.format(namespace, view_name))

if kwargs:
return reverse(kwargs=kwargs)
elif args:
return reverse(args=args)
else:
return reverse()
# We're explicitly NOT happy to just re-raise the exception, as that may
# adversely affect stack traces.
if 'default' not in kwargs:
if kwargs:
return reverse(kwargs=kwargs)
elif args:
return reverse(args=args)
else:
return reverse()

default = kwargs.pop('default', None)
try:
if kwargs:
return reverse(kwargs=kwargs)
elif args:
return reverse(args=args)
else:
return reverse()
except NoReverseMatch:
return default

0 comments on commit 4807741

Please sign in to comment.