我想在我的 django 元素的 html 模板中添加一个 if
函数。
如果变量datas为空,则显示文本“The results is null”,如果变量datas不为空,则显示datas中数据的表格。
这是我写的,但是它引发了错误
Invalid block tag on line 13: 'if(isEmpty($('#datas')))', expected 'endblock'.
Did you forget to register or load this tag?
我该如何处理?
{% if(isEmpty($('#datas'))) %}
<h3>The results is null.</h3>
{% else %}
<table style="table-layout:fixed;">
<tr>...</tr>
<tr>
{% for i in datas %}
<td>{{ i.1 }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
最佳答案
我想你可以使用 empty标签。像这样使用它:
<table style="table-layout:fixed;">
<tr>...</tr>
<tr>
{% for i in datas %}
<td>{{ i.1 }}</td>
</tr>
{% empty %}
<h3>The results is null.</h3>
{% endfor %}
但是,如果您想事先检查 datas
是否为空,那么我认为最好在 View 中进行。你可以这样尝试:
def some_view(request):
context = {}
datas = Data.objects.all()
if datas.exists():
context['data_exists'] = True
context['datas'] = datas
return render(request, 'template.html', context)
并使用它的模板:
{% if not data_exists %}
<h3>The results is null.</h3>
{% else %}
....
关于html - 如何在django html模板中添加if函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53680312/