我想知道如何在模板中获得当前URL。
假设我当前的URL是:
.../user/profile/
如何将此返回到模板?
我想知道如何在模板中获得当前URL。
假设我当前的URL是:
.../user/profile/
如何将此返回到模板?
当前回答
我想发送到模板完整的请求有点多余。我这样做
from django.shortcuts import render
def home(request):
app_url = request.path
return render(request, 'home.html', {'app_url': app_url})
##template
{{ app_url }}
其他回答
如果你也在模板中使用js,你可以这样做: 在你的js
document.addEventListener('DOMContentLoaded', function() {
...
getUrl();
}
function getUrl() {
let someDiv = document.querySelector(`#someDiv`);
someDiv.innerHTML = window.location.href;
}
对于你的模板
...
<div id="someDiv"><div>
...
我想发送到模板完整的请求有点多余。我这样做
from django.shortcuts import render
def home(request):
app_url = request.path
return render(request, 'home.html', {'app_url': app_url})
##template
{{ app_url }}
下面的代码帮助我:
{{ request.build_absolute_uri }}
使用的例子:
<!-- 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>
如果你正在使用渲染部分,最好使用
{{请求。path_info}}
它返回页面的确切url