Django template, if tag based on current URL value
I want to be able to do an if tag based on the current URL value.
for example, if the current page's url is accounts/login/
then don't show a link, without passing a variable from the view.
I am not sure how I can write an {% if %}
tag for开发者_JS百科 this, is it possible?
You can also do this for dynamic urls using:
{% url 'show_user_page' user=user as the_url %}
{% if request.get_full_path == the_url %}something{% endif %}
where your urls.py contains something like:
(r'^myapp/user/(?P<user>\d+)/$', 'show_user_page'),
I know this because I just spent ages drafting a stackoverflow question, when I found the answer in the docs.
I'd say even in simple cases this might be the better approach, because it is more loosely coupled.
If you pass the "request" object to your template, then you are able to use this:
{% if request.get_full_path == "/account/login/" %}
For dynamic urls, you can also use the request.resolver_match
attribute (docs):
HttpRequest.resolver_match
An instance of ResolverMatch representing the resolved URL. This attribute is only set after URL resolving took place, which means it’s available in all views but not in middleware which are executed before URL resolving takes place (you can use it in process_view() though).
The returned ResolverMatch
object has many useful attributes, such as the view_name
attribute, which returns the same name you would have passed to the url
templatetag to generate the current url.
view_name
The name of the view that matches the URL, including the namespace if there is one.
See the docs for this and other attributes.
Applying this to the example from @nimasmi's answer, you would get:
{% if request.resolver_match.view_name == 'show_user_page' %}something{% endif %}
where your urls.py contains something like:
(r'^myapp/user/(?P<user>\d+)/$', 'show_user_page'),
Note that when you use URL namespaces, view_name
will return the namespace qualified url/view name, e.g. app:urlname
.
Compared to the answer by @nimasmi, this simplifies the template code a bit, by not needing the separate {% url %}
tag to generate the url to compare with. This is especially true when you do not need to compare view parameters, just the view name. If you do need to compare parameters in the url, you can easily use the ResolverMatch.args
and kwargs
attributes, though.
Maybe like this?
if "order" in request.path
Using "in" allows you to match URLs like:
customers, customer, customer/new, customer/edit, etc
<ul class="nav nav-pills nav-fill">
<li class="nav-item">
<a class="nav-link
<pre>{% if "order" in request.path %} active {% endif %} "</pre>
href="/orders">Order List</a>
</li>
<li class="nav-item">
<a class="nav-link
<pre>{% if "customer" in request.path %} active {% endif %} "</pre>
href="/customers">Customer List</a>
</li>
<li class="nav-item">
<a class="nav-link
<pre>{% if "product" in request.path %} active {% endif %} "</pre>
href="/products">Product List</a>
</li>
</ul>
精彩评论