Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if url matches in template

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

like image 363
szaman Avatar asked Jun 20 '11 07:06

szaman


2 Answers

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.

like image 106
mattoc Avatar answered Sep 24 '22 00:09

mattoc


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.

like image 41
Max Peterson Avatar answered Sep 21 '22 00:09

Max Peterson