我对html和Django的了解非常有限,但是我有这个Django项目,其中包含多个(12)HTML页面,这些页面在类似于以下代码的表中显示信息。如果有需要修复的内容,将有条件地显示该表。如果修复程序中的任何数据已经过测试,则应以红色突出显示以避免编辑。我最近添加了<tr {% if p.tested in green_tested %} bgcolor="red" {% endif %}>
一点来进行突出显示,但是必须手动将其添加到所有12页中确实很愚蠢。有没有一种方法可以将其添加为外部模板的一部分?
{% extends "admin/base_site.html" %}
{% load static %}
{% block content %}
<p><b>Description:</b> {{ docstring }}</p>
{% if count|length %}
<p><b>Action:</b> Investigate why and fix.</p>
<p style="color:red">If any table rows are highlighted red, indicating a tested profile, flag immediately to health report owner/Automation before editing.</p>
<table>
<tr bgcolor="#ccc">
<th>Profile</th>
<th>Name</th>
<th>Type</th>
<th>Tested</th>
<th>e.g. Device</th>
</tr>
{% for p in count %}
<tr {% if p.tested in green_tested %} bgcolor="red" {% endif %}>
<td><a href={{ p.profile_url }}>{{ p.url }}</a></td>
<td>{{ p.name }}</td>
<td>{{ p.type }}</td>
<td>{{ p.tested }}</td>
<td><a href={{ p.device_url }}>{{ p.dev_id }}</a></td>
{% endfor %}
</tr>
</table>
{% else %}
No fixes left to make!
{% endif %}
{% endblock %}
我在views.py中的函数如下所示:
def test_function(request):
count = test_function_count()
context = {'count': count,
'green_tested': list(map(lambda x: x[0], models.GREEN_TESTED)),
'docstring': test_function_count.__doc__}
return render(request, 'health_report/test-function-page.html', context)
不必'green_tested'
在视图中的所有函数中添加,这也很好。
对于green_tested
每种视图中的问题,我建议使用上下文处理器。首先,您必须在view.py所在的位置创建一个新文件context_processors.py。像这样:
def function_name(request):
data = # here put logic you want
return {
'context_data': data
}
然后,您需要在TEMPLATES中的settings.py文件中注册上下文处理器。模式是:YourAppName.FileName.FunctionName
这里的示例(我不替换,YourAppName
因为我不知道):
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['YourAppName/templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# Here is new line
'YourAppName.context_processor.function_name',
],
},
},
]
然后,您可以在任何模板中使用{{ context_data }}
,函数返回的字典中键的名称。
对于主要问题,我只有一个建议。您可以创建某种父模板,例如“ base_site.html”。base_site.html和当前模板之间的内容。但是您要放置的行位于中间的某个位置,因此我不确定这是否对您有用,或者这些模板之间的相似之处。比将这条线放置12次要麻烦得多。
{% extends "admin/base_site.html" %}
{% load static %}
{% block content1 %}
{% endblock %}
Here the code you want in each template.
{% block content2 %}
{% endblock %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句