开发者

Check if url matches in template

Is it possible to check in t开发者_开发知识库emplate that some url match any pattern from urls?


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.


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.


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


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!'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜