【发布时间】:2018-07-07 21:37:04
【问题描述】:
我试图通过不同的块或包含方法在一个模板中使用更多不同的视图,但我卡住了。我的目标是将我的不同视图实现到一个模板中。我尝试了更多解决方案,但这些对我没有用。我展示了这些解决方案:
我的看法:
def dashboard_data(request):
# Here I collect data from my PostgreSQL database I push these into
#Objects and I send it to my test_a.html via render like below.
return render(request, 'my_project/test_a.html', send_data)
def chart_data(request):
#In these view my final goal is to collect data from database and create
#charts but for the simplicity I just use a list (a=[1,2,3,4]) and I
#push it to the test_b.html and I render it.
render(request, 'my_project/test_b.html', send_data))
我的模板:
1、base.html
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}<title>My project</title>{% endblock %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Include CSS files -->
{% load static %}
<!-- Include CSS files -->
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'css/bootstrap-table.css' %}">
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}">
</head>
<body>
{% block sidebar %}
{% endblock %}
{% block content%}
{% endblock %}
</body>
</html>
1、test_a.html
{% extends "monitor/base.html" %}
{%block content%}
{%for i in table%}
<p> {{i.record}}</p>
{%endfor%}
{%endblock}
2、测试b.html
{%for i in a%}
<p> {{i}}</p>
{%endfor}
所以我的目标是 test_b.html 的结果可以出现在 base.html 中。
我的解决方案:
A:我尝试将test_b.html放入一个块并集成到base.html中
1、base.html (test1):
{% block conent%}
{% endblock %}
{% block chart%}
{% endblock %}
1、test_b.html (test1):
{% extends "monitor/base.html" %}
{%block chart%}
{%for i in a%}
<p> {{i}}</p>
{%endfor}
{%endblock%}
B:我尝试使用{{ block.super }}
1、base.html (test1):
{% block conent%}
{% endblock %}
1、test_b.html (test1):
{% extends "monitor/base.html" %}
{%block content%}
{{ block.super }}
{%for i in a%}
<p> {{i}}</p>
{%endfor}
{%endblock%}
C: 最后我也使用了 include 方法,但我也没有为我工作。在这里,我尝试在 test_b.html 中使用简单的 html 标签,如 (<p>Hello world</p>) 并工作。因此,如果我不使用变量,它可以工作,但我必须从我的视图中使用我的变量。
1、test_a.html
{% extends "monitor/base.html" %}
{%block chart%}
{%for i in a%}
<p> {{i}}</p>
{%endfor}
{%endblock%}
{% include "my_project/test_b.html" %}
2、test_b.html
{%for i in a%}
<p> {{i}}</p>
{% endfor %}
【问题讨论】:
-
你不能同时渲染两个视图,一个视图只是一个返回响应的可调用对象,但是你可以在一个视图中调用不同的函数!另一种方法是使用 context_processor,但只有当您需要在所有视图中都可以访问数据时才必须使用它。
标签: html django django-templates block