Is it possible to check in template 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With