检查url是否与模板匹配

sza*_*man 5 django django-templates

是否可以在模板中检查某些网址是否与网址中的任何模式匹配?

Max*_*son 7

您可以使用url标记的"as"形式来检查命名URL是否存在.

{% url path.to.view as the_url %}
{% if the_url %}
  <a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

当使用"as"时,它不会引发异常.


小智 6

这是您通常希望在views.py文件中执行的操作,其中包含带有已知args或resolve()的命名URL 的reverse()帮助程序.

如果您确实需要在模板中专门使用此功能,这是一个hacky解决方案:

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

注意:这并不能保证URL有效,只是存在模式匹配.