yung peso
yung peso

Reputation: 1796

Django - Would I be able to use template tags for rendering HTML given URL path conditionals?

I have a blog page with the path /articles/. I would like to use conditional statements to reflect HTML renders.

For example, my blog uses a paginator for blog posts. The paginator uses a URL query to retrieve the next page of post objects like so: /articles/?page=2

I would like for the next page to stylize the HTML template differently, hence my reasoning for using a conditional statement.

Here is my template that I use:

{% if request.path == '/articles/' %}
# Render HTML only meant for the above path



{% elif request.path != '/articles/'%} 
# Render HTML for paths that are NOT the exact match above, such as pagination URLs, 
# search querys, categories filtering, etc...

{% endif %}

My current bug is that I'm only rendering the first statement: if request.path == '/articles/' for everything, even non exact matches.

So this URL path: /articles/?page=2 is rendering: {% if request.path == '/articles/' %} when it should be rendering the elif {% elif request.path != '/articles/'%} due to the not equals sign.

Is the above possible to do with only HTML template tags? I know I can use urls.py and edit views but I'm using wagtail CMS and playing with the template seems like the most easiest thing to do right now.

Upvotes: 1

Views: 302

Answers (1)

gasman
gasman

Reputation: 25292

request.path does not include the '?...' querystring part of the URL, so this is working as designed - the path portion of the URL /articles/?page=2 is /articles/.

Django compiles the querystring into the dictionary request.GET, so one way of doing what you want is to check whether that dictionary is empty or not:

{% if not request.GET %}
    request is for the plain URL /articles/
{% else %}
    request has a querystring parameter on it
{% endif %}

Upvotes: 1

Related Questions