我想知道如何在模板中获得当前URL。
假设我当前的URL是:
.../user/profile/
如何将此返回到模板?
我想知道如何在模板中获得当前URL。
假设我当前的URL是:
.../user/profile/
如何将此返回到模板?
当前回答
你可以使用{{request.path}}获取不带参数的url。 你可以使用{{request.get_full_path}}来获取带参数的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 1.9及以上版本:
## template
{{ request.path }} # -without GET parameters
{{ request.get_full_path }} # - with GET parameters
Old:
## settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
## views.py
from django.template import *
def home(request):
return render_to_response('home.html', {}, context_instance=RequestContext(request))
## template
{{ request.path }}
要将get参数传递给模板, 你可以通过views.py文件传递它
例子:
return render(request, 'test.html',{'get_parameter_name' : get_parameter_value})
并在模板中使用如下:
{{get_parameter_name}}
在django模板中 简单地从{{request.path}}获取当前url 获取参数为{{request.get_full_path}}的完整url
注意: 你必须在django TEMPLATE_CONTEXT_PROCESSORS中添加request
你可以使用{{request.path}}获取不带参数的url。 你可以使用{{request.get_full_path}}来获取带参数的url。