在Django中使用不同的模板来呈现相同的URL模式

2024-10-03 00:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题类似于Same URL in multiple views in Django,但我不是基于用户身份验证来呈现模板,而是基于浏览器中启用或禁用的JavaScript。在

我想做什么?

如果在浏览器中启用了JavaScript,我将尝试呈现index.html页面,否则,如果禁用了jsDisabled.html页面,并且这两个页面都应该在相同的URL模式下呈现,例如:

如果在浏览器中启用了JavaScript,localhost:8000应该呈现index.html,或者如果JavaScript被禁用,它应该呈现jsDisabled.html页面。在

注意:我正在检查JavaScript是否在浏览器中被禁用,方法是使用在JavaScript被禁用时运行的<noscript>标记。

以下是我目前为止的代码:

基本.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>

网址.py:

^{pr2}$

视图.py:

from django.shortcuts import render

def index(request, flag):
    if (flag):
       return render(request, 'jsDisabled.html')
    else:
       return render(request, 'index.html')

Tags: inlocalhosturlindexrequesthtml浏览器body
2条回答

经过大量调试,我终于找到了解决方案:)这就是:

在基本.html:

{% 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>

在网址.py

^{pr2}$

在视图.py:

from django.shortcuts import render

def index(request):
    return render(request,'index.html')

def temp(request):
     return render(request,'temp.html')

我在templates文件夹中创建了一个名为includes的文件夹,并将jsDisabled.html放在其中,从而将include内置模板标记作为{% include 'includes/jsDisabled.html' %}建议的{% include 'includes/jsDisabled.html' %}。在

根据您的Django版本,您可能需要指定TEMPLATE_DIR=in设置.py(在较新版本中,这是不需要的)。在

下面是一些关于模板和标记逻辑的有用的information

Main/templates/myapp/base.html
Main/templates/myapp/index.html
Main/templates/myapp/includes/yes_js.html
Main/templates/myapp/includes/no_js.html

在基本.html:

^{pr2}$

在索引.html:

{% extends 'myapp/base.html' %}
{% load staticfiles %}

{% block content %}
<noscript>
{% include 'no_js.html' %}
</noscript>

{% include 'yes_js.html' %}

{% endblock %}

相关问题 更多 >