我想知道如何在模板中获得当前URL。

假设我当前的URL是:

.../user/profile/

如何将此返回到模板?


当前回答

如果你也在模板中使用js,你可以这样做: 在你的js

document.addEventListener('DOMContentLoaded', function() {
    ...
    getUrl();
}

function getUrl() {
    let someDiv = document.querySelector(`#someDiv`);
    someDiv.innerHTML = window.location.href;
}

对于你的模板

...
<div id="someDiv"><div>
...

其他回答

如果你正在使用渲染部分,最好使用

{{请求。path_info}}

它返回页面的确切url

使用的例子:

 <!-- BRAND -->
        <div class="brand">
            <div class="logo">
                {% if request.get_full_path == '/' %}
                    <a href="{% url 'front:homepage' %}" class="first-logo big-logo">
                        <img src="{% static 'assets/images/logo-big.svg' %}"
                             alt="pozitiv">
                    </a>

                    <a href="{% url 'front:homepage' %}" class="second-logo mobile-logo">
                        <img src="{% static 'assets/images/logo.svg' %}"
                             alt="<?php echo WEBSITE_NAME; ?>" >
                    </a>

                {% else %}

                    <a href="{% url 'front:homepage' %}">
                        <img src="{% static 'assets/images/logo.svg' %}"
                             alt="<?php echo WEBSITE_NAME; ?>" style="width: 320px; margin: -20px 0 0 0;">
                    </a>
                {% endif %}
            </div>
        </div>

在django模板中 简单地从{{request.path}}获取当前url 获取参数为{{request.get_full_path}}的完整url

注意: 你必须在django TEMPLATE_CONTEXT_PROCESSORS中添加request

3 . Django > 我不改变设置或任何东西。 我在模板文件中添加了下面的代码。

{{ request.path }}  #  -without GET parameters 
{{ request.get_full_path }}  # - with GET parameters

在view.py中将请求变量传递给模板文件。

view.py:

def view_node_taxon(request, cid):
    showone = get_object_or_404(models.taxon, id = cid)
    context = {'showone':showone,'request':request}
    mytemplate  = loader.get_template('taxon/node.html')
    html = mytemplate.render(context)
    return HttpResponse(html)

下面的代码帮助我:

 {{ request.build_absolute_uri }}