[英]Rendering different templates to the same URL pattern in Django
我的问题类似于Django中多个视图中的Same URL ,但是我不是基于user_authentication呈现模板,而是基于浏览器中启用或禁用的JavaScript呈现模板。
我要做什么?
如果尝试在浏览器中启用JavaScript,我将尝试呈现index.html
页面,否则,如果禁用jsDisabled.html
页面,并且两个页面均应使用相同的URL模式呈现,则我想呈现该页面。例如:
如果在浏览器中启用了JavaScript,则localhost:8000
应该呈现index.html
如果禁用JavaScript,则应该呈现jsDisabled.html
页面。
注意:我正在使用<noscript>
标记检查浏览器中是否禁用了JavaScript,该标记将在禁用JavaScript时运行。
到目前为止,这是我的代码:
base.html文件:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body class="noJs">
...
<a href="{% url 'index' 0 %}"> abc </a>
...
<noscript>
<style type="text/css">
.noJs {
display: none;
}
</style>
<meta http-equiv="refresh" content="{% ulr 'index' 1 %}"> /* This should render jsDisabled.html page on the same URL which is 'localhost:8000' */
</noscript>
</body>
</html>
urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
...
url(r'^(?P<flag>[0-1])$', views.index, name='index'),
]
views.py:
from django.shortcuts import render
def index(request, flag):
if (flag):
return render(request, 'jsDisabled.html')
else:
return render(request, 'index.html')
根据您的Django版本,您可能需要在settings.py中指定TEMPLATE_DIR =(在较新的版本中,这不是必需的)。
以下是有关模板和标签逻辑的一些有用信息 :
Main/templates/myapp/base.html
Main/templates/myapp/index.html
Main/templates/myapp/includes/yes_js.html
Main/templates/myapp/includes/no_js.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
{% extends 'myapp/base.html' %}
{% load staticfiles %}
{% block content %}
<noscript>
{% include 'no_js.html' %}
</noscript>
{% include 'yes_js.html' %}
{% endblock %}
经过大量的调试,我终于找到了解决方案:)在这里:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="noJs">
...
<a href="{% url 'index' 0 %}"> abc </a>
...
</div>
<noscript>
<style type="text/css">
.noJs {
display: none;
}
</style>
{% include 'includes/jsDisabled.html' %}
</noscript>
</body>
</html>
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^articles/', include('articles.urls')),
url(r'^contact/', include('contact.urls')),
url(r'^temp/',views.temp, name="temp"),
url(r'^$', views.index, name='index'),
]
from django.shortcuts import render
def index(request):
return render(request,'index.html')
def temp(request):
return render(request,'temp.html')
通过在模板文件夹内创建一个名为includes
的文件夹并将jsDisabled.html
放在其中,我将@ noes1s建议的include内置模板标签{% include 'includes/jsDisabled.html' %}
为{% include 'includes/jsDisabled.html' %}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.