我想知道如何在模板中获得当前URL。
假设我当前的URL是:
.../user/profile/
如何将此返回到模板?
我想知道如何在模板中获得当前URL。
假设我当前的URL是:
.../user/profile/
如何将此返回到模板?
当前回答
使用的例子:
<!-- 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>
其他回答
你可以使用{{request.path}}获取不带参数的url。 你可以使用{{request.get_full_path}}来获取带参数的url。
下面的代码帮助我:
{{ request.build_absolute_uri }}
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)
在django模板中 简单地从{{request.path}}获取当前url 获取参数为{{request.get_full_path}}的完整url
注意: 你必须在django TEMPLATE_CONTEXT_PROCESSORS中添加request
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 }}