首页 > 解决方案 > Django - How to get current url from template and replace parameter value or delete parameter and append after

问题描述

In my django template I need to get the current url and modify a parameter value or add this parameter if not present.

here's an url example : /articles/pdf?perpage=2&page=2

All I know so far is how to retrieve the whole url :

{{ request.get_full_path }}

But what I need to do is to be able to create a new url that I will use as an href in which if "page" parameter present, I change its value, or if not present, I append this parameter to the url.

EDIT : Is it that hard that no one knows how to do this ?....

标签: pythondjangodjango-templates

解决方案


因为这似乎是一个难题......我必须找到一种解决方法来实现它。

我剪切了所有形式的“page”参数,然后将新参数附加到 href 中:

{% define request.GET.page as page_num %}
{% define "?page="|add:page_num as page_first_param %}
{% define "&page="|add:page_num as page_next_param %}
{% define request.get_full_path|cut:page_first_param|cut:page_next_param as new_partial_url %}
{% if '?' in new_partial_url %} {% define "&" as p %} {% else %} {% define "?" as p %} {% endif %}
{% define new_partial_url|add:p as new_full_url %}
                
    <a class="page-link" href="{{ new_full_url }}page={{ items.previous_page_number}}">
    « Précédent</a>

推荐阅读