1

Just wondering what the correct syntax is for checking if the current path is equal to some url:

{% if request.path == url "app_namespace:route_name" %}

Above doesn't work - but hoping someone knows a way or method for doing this lookup...

GCien
  • 2,221
  • 6
  • 30
  • 56
  • Possible duplicate of [Django Templates: Comparing current url with {% url xyz %}](https://stackoverflow.com/questions/7593669/django-templates-comparing-current-url-with-url-xyz) – Mazel Tov Feb 03 '18 at 19:53

1 Answers1

2

You can use this syntax to save the url path in a template variable:

{% url 'app_namespace:route_name' as url_path %}

which you can later use within your if condition

{% if request.path == url_path %}...{% endif %}

Note that you may also find this syntax useful when you need to use the output of a url function within a blocktrans block:

{% blocktrans %}
    <a href="{{ url_path }}">text to translate</a>
{% endblocktrans %}
bonidjukic
  • 1,461
  • 1
  • 13
  • 19
  • Didn't quite work - 'app_namespace:route_name' is being interpreted as a string... – GCien Feb 03 '18 at 22:35
  • @MichaelRoberts Well, yeah, you do have to check it against a hardcoded value, right? Otherwise, I'm not sure what you're trying to accomplish here. – bonidjukic Feb 03 '18 at 22:48
  • No - as in it’s just checking url_name == app_namespace:route_name ... I want to check it against what {% url app_namespace:route %} evaluates to. – GCien Feb 04 '18 at 01:49
  • 1
    I can't really figure out what exactly are you trying to accomplish here. You could also try with `{% url 'app_namespace:route_name' as url_path %}` and then use check against it with `{% if request.path == url_path %}`. – bonidjukic Feb 04 '18 at 10:06
  • @MichaelRoberts Please take a look - I updated the answer. – bonidjukic Feb 05 '18 at 09:30
  • Awesome, glad to have helped. – bonidjukic Feb 06 '18 at 09:56