szaman
szaman

Reputation: 6756

Check if url matches in template

Is it possible to check in template that some url match any pattern from urls?

Upvotes: 6

Views: 5698

Answers (4)

mattoc
mattoc

Reputation: 712

This is something you'd normally want to do in a views.py file with the reverse() helper for named URLs with known args or resolve() for paths.

If you do need this functionality in a template specifically, here is a hacky solution:

@register.simple_tag
def urlpath_exists(path):
    """Returns True for successful resolves()'s."""
    try:
        return bool(resolve(path))
    except Resolver404:
        return False

Note: this doesn't guarantee that the URL is valid, just that there was a pattern match.

Upvotes: 9

Max Peterson
Max Peterson

Reputation: 673

You can use the "as" form of the url tag to check if a named URL exists.

{% url path.to.view as the_url %}
{% if the_url %}
  <a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}

When "as" is used it does not raise an exception.

Upvotes: 10

Hgeg
Hgeg

Reputation: 545

Let's say that your project name is dummy. Then,

from dummy.urls import urlpatterns
def find_url(url):
  for e in urlpatterns:
    if e.regex.match(url):
      print 'found!'  #or do whatever you want
      return          #then exit the procedure.
  print 'not found!'

Upvotes: 1

szaman
szaman

Reputation: 6756

I assume that there is not simple method to do this. So I wrote a simple templatetag which takes url name and call reverse method for it and put reverse into try..except:

try:
    result = reverse(url)
except:
    result = None
return result

Upvotes: 1

Related Questions