Check if url matches in template

左心房为你撑大大i 提交于 2019-12-22 07:06:11

问题


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


回答1:


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(name):
    """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.




回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/6407808/check-if-url-matches-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!